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.
Problem
Section titled “Problem”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).
Solution
Section titled “Solution”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.
Applicability
Section titled “Applicability”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.
Implementation
Section titled “Implementation”The steps to implement this pattern are:
- Create the prototype interface and declare the
clonemethod in it. - 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 & Cons
Section titled “Pros & Cons”| Pros |
|
|---|---|
| Cons | Cloning complex objects that have circular references might be very tricky. |