Skip to content

Prototype Design Pattern

Creational design pattern

Creational pattern

Prototype (or Clone) design pattern lets you copy existing objects without making your code dependent on their classes.

You have an object you want to create an exact copy of.

Private fields and methods are not visible from outside the object so it’s hard to copy them. Your code becomes dependent on the class you’re trying to copy since you have to know the object’s class to create a duplicate.

Moreover, sometimes you only know the interface that the object follows, but not its concrete class (i.e. a parameter in a method accepts any objects that follow the same interface).

This pattern delegates the cloning process to the actual objects that are being cloned. The pattern declares a common interface for all objects that support cloning.

Usually, such an interface contains just a single clone method. The method creates an object of the current class and carries over all the field values of the old object into the new one. You can copy private fields too: most programming languages let objects access private fields of other objects that belong to the same class.

An object that supports cloning is called a prototype. When your objects have a lot of fields and many of possible configurations, cloning them might be an alternative to subclassing.

A good analogy to this pattern is the process of mitotic cell division. After this process, a pair of identical cells is formed. The original cell acts as a prototype and takes an active role in creating the copy.

Use the Prototype pattern when:

  • your code should not depend on the concrete classes of objects that you need to copy,
  • you want to reduce the number of subclasses that only differ in the way they initialize their respective objects.

The steps to implement this pattern are:

  1. Create the prototype interface and declare the clone method in it.
  2. Within each prototype classes, create an alternative constructor that accepts an object of that class as an argument. The constructor must copy the values of all fields defined in the class from the passed object into the newly created instance.

The cloning method usually consists of just one line: it runs a new operator with the prototypical version of the constructor. Every class must explicitly override the cloning method and use its own class name, otherwise the cloning method may produce an object of a parent class.

Pros
  1. You can clone objects without coupling them to their concrete classes.
  2. You can get rid of repeated initialization code in favor of cloning pre-built prototypes.
  3. You can produce complex objects more conveniently.
  4. You get an alternative to inheritance when dealing with configuration presets for complex objects.
ConsCloning complex objects that have circular references might be very tricky.