Prototype Pattern is used to create duplicate objects while ensuring performance. This type of design pattern is a creation pattern, which provides the best way to create objects.
This pattern implements a prototype interface, which is used to create a clone of the current object. This mode is adopted when the cost of creating objects directly is high. For example, an object needs to be created after a costly database operation. We can cache the object, return its clone on the next request, and update the database when necessary to reduce database calls.
intention
Use prototype instances to specify the kind of objects to create, and create new objects by copying these prototypes.
Realization
- Implementing the clonable method
public class Shape implements Cloneable{
protected String type;
public void show(){
System.out.println(type);
}
@Override
protected Shape clone() throws CloneNotSupportedException {
Shape shape = (Shape) super.clone();
return shape;
}
}
- Create entity class
public class Circle extends Shape{
public Circle(){
type = "Circle="+this.hashCode();
}
}
public class Rectangle extends Shape{
public Rectangle(){
type = "Rectangle="+this.hashCode();
}
}
- Use
public static void main(String... args) {
Circle circle = new Circle();
Rectangle rectangle = new Rectangle();
circle.show();
rectangle.show();
System.out.println("==================");
try {
Circle c = (Circle) circle.clone();
c.show();
Rectangle r = (Rectangle) rectangle.clone();
r.show();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
- Result
I/System.out: Circle=1249794168
I/System.out: Rectangle=1249794268
I/System.out: ==================
I/System.out: Circle=1249794168
I/System.out: Rectangle=1249794268