Design Patterns#3 Prototype Pattern

Burak KOCAK
2 min readFeb 5, 2023

--

Design Patterns

The Prototype pattern is a creational design pattern in Java that allows an object to be cloned or copied to create a new instance of the same class. The Prototype pattern allows objects to be created without specifying the exact class of object that will be created.

In this pattern, a “prototype” instance is created and then cloned to create new instances. The cloning process is typically implemented by creating a shallow or deep copy of the prototype instance.

This pattern is useful when creating an object is time-consuming or when creating an instance of a class requires knowledge of its dependencies. By cloning an existing instance, you can avoid the overhead of creating a new object from scratch and you can also ensure that the new instance has the same state as the original instance.

Here’s a simple example of the Prototype pattern in Java:

interface Prototype {
Prototype getClone();
}

class ConcretePrototypeA implements Prototype {
@Override
public Prototype getClone() {
return new ConcretePrototypeA();
}
}

class ConcretePrototypeB implements Prototype {
@Override
public Prototype getClone() {
return new ConcretePrototypeB();
}
}

public class PrototypeExample {
public static void main(String[] args) {
Prototype prototypeA = new ConcretePrototypeA();
Prototype cloneA = prototypeA.getClone();

Prototype prototypeB = new ConcretePrototypeB();
Prototype cloneB = prototypeB.getClone();
}
}

In this example, the Prototype interface defines the getClone method that returns an instance of the same class. The ConcretePrototypeA and ConcretePrototypeB classes implement this method to return new instances of their respective classes. In the main method, we create objects of type ConcretePrototypeA and ConcretePrototypeB and use the getClone method to create new instances of these classes.

--

--