Prototype Pattern
The Prototype pattern is a creational design pattern that allows an object to clone itself. This pattern is used when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects.
This pattern is especially useful when you want to avoid subclasses of an object creator in the client application. It provides a simple way to copy existing objects independent of the specific classes of the objects.
In the Prototype pattern, you would have an abstract base class, and concrete classes would implement a clone()
method that creates a new instance of itself. This can be done in Java, for example, by implementing the Cloneable
interface and overriding the clone()
method from the Object
class.
Here's a simple example:
abstract class Prototype implements Cloneable {
abstract Prototype clonePrototype();
}
class ConcretePrototype extends Prototype {
private String field;
ConcretePrototype(String field) {
this.field = field;
}
@Override
Prototype clonePrototype() {
try {
return (ConcretePrototype) super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return null;
}
@Override
public String toString() {
return field;
}
}
public class Client {
public static void main(String[] args) {
ConcretePrototype prototype1 = new ConcretePrototype("Prototype 1");
ConcretePrototype prototype2 = (ConcretePrototype) prototype1.clonePrototype();
System.out.println(prototype1);
System.out.println(prototype2);
}
}
In this example, ConcretePrototype
is the concrete class implementing the clonePrototype()
method. This method creates a new instance of ConcretePrototype
by calling the super.clone()
method, which effectively creates a copy of the current object.
The Client
class shows how to use the Prototype pattern: by cloning prototype1
, you get a prototype2
which is a copy of prototype1
.
The Prototype pattern is particularly useful when object initialization is costly, and you anticipate making many copies of your objects, thereby saving significant resources.