Prototype design pattern is a creational pattern that allows you to create new objects by copying or cloning existing objects, without knowing their specific class. It’s like making a photocopy of something instead of creating it from scratch.
Key components of the Prototype pattern include:
- Prototype Interface: Defines a method for cloning itself, typically named something like
clone()
. - Concrete Prototypes: Implement the cloning method defined in the prototype interface to create copies of themselves.
- Client: Requests to create new objects by cloning existing prototypes, rather than creating them directly.
~:Sample code for Prototype design pattern:~
// Prototype interface
interface CarPrototype {
CarPrototype clone();
void configure(String color, String engine, String wheels);
void printDetails();
}
// Concrete prototype: Car
class Car implements CarPrototype {
private String color;
private String engine;
private String wheels;
public Car() {
// Default constructor
}
// Clone method
public CarPrototype clone() {
Car clonedCar = new Car();
clonedCar.setColor(this.color);
clonedCar.setEngine(this.engine);
clonedCar.setWheels(this.wheels);
return clonedCar;
}
// Configure method
public void configure(String color, String engine, String wheels) {
this.color = color;
this.engine = engine;
this.wheels = wheels;
}
// Print details method
public void printDetails() {
System.out.println("Car Details:");
System.out.println("Color: " + color);
System.out.println("Engine: " + engine);
System.out.println("Wheels: " + wheels);
System.out.println();
}
// Getters and setters
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getEngine() {
return engine;
}
public void setEngine(String engine) {
this.engine = engine;
}
public String getWheels() {
return wheels;
}
public void setWheels(String wheels) {
this.wheels = wheels;
}
}
// Client code
public class Main {
public static void main(String[] args) {
// Create a prototype car
CarPrototype prototypeCar = new Car();
prototypeCar.configure("Red", "V6", "Alloy");
// Clone the prototype car to create new instances
CarPrototype car1 = prototypeCar.clone();
CarPrototype car2 = prototypeCar.clone();
// Print details of the cloned cars
car1.printDetails();
car2.printDetails();
}
}