The Prototype pattern is a creational pattern that allows you to create new objects by cloning an existing object. This pattern is useful when you need to create many objects that are similar to an existing object, but with some differences.
In the following example, we will create a prototype for a Car object:
import java.util.ArrayList;
import java.util.List;
public class Car implements Cloneable {
private List<String> parts;
public Car() {
parts = new ArrayList<>();
}
public void addPart(String part) {
parts.add(part);
}
public List<String> getParts() {
return parts;
}
@Override
public Car clone() {
Car cloned = new Car();
List<String> clonedParts = new ArrayList<>();
for (String part : parts) {
clonedParts.add(part);
}
cloned.parts = clonedParts;
return cloned;
}
}
public class Main {
public static void main(String[] args) {
Car original = new Car();
original.addPart("engine");
original.addPart("wheels");
original.addPart("doors");
Car cloned = original.clone();
cloned.addPart("seats");
System.out.println(original.getParts()); // prints ["engine", "wheels", "doors"]
System.out.println(cloned.getParts()); // prints ["engine", "wheels", "doors", "seats"]
}
}
In this example, we have a Car class that implements the Cloneable interface to enable cloning. The Car class has a list of parts, and methods for adding and getting parts. It also overrides the clone() method to create a new Car object with the same parts as the original Car object.
In the main() method, we create an original Car object and add some parts to it. We then clone the original Car object to create a new Car object with the same parts, and add a new part to the cloned Car object. Finally, we output the parts of both Car objects using the getParts() method.
The benefit of using the Prototype pattern is that it allows you to create new objects by cloning an existing object, which can save time and resources compared to creating a new object from scratch. It also provides a way to create new objects with similar properties to an existing object, while allowing you to modify the new object’s properties without affecting the original object.