Understanding the Prototype Design Pattern in Java
The Prototype Design Pattern is a creational design pattern that involves creating new objects by copying existing ones, known as prototypes. It is especially useful when object creation is costly or complex, and there is a need to avoid the overhead of recreating objects from scratch.
In this post the Prototype Pattern is explained with practical examples including object cloning and registry of prototypes.
What is the Prototype Design Pattern?
The Prototype Pattern allows objects to create copies of themselves. This eliminates the need for the client to know the details of object creation and helps in duplicating objects efficiently.
When to Use Prototype Pattern
- When the cost of creating a new object is expensive or complex.
- When you want to avoid subclasses for object creation.
- When objects need to be created dynamically at runtime.
Key Components
- Prototype Interface: Declares a method for cloning itself, typically a
clone()method. - Concrete Prototype Classes: Implement the clone method to duplicate themselves.
- Client: Uses the prototype to create new objects by cloning instead of instantiation.
- Prototype Registry (Optional): Stores and manages existing prototype instances to facilitate cloning.
Java Code Example
public abstract class Shape implements Cloneable {
private String id;
protected String type;
abstract void draw();
public String getType() {
return type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
// Clone method
public Object clone() {
Object clone = null;
try {
clone = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return clone;
}
}
public class Rectangle extends Shape {
public Rectangle() {
type = "Rectangle";
}
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
public class Square extends Shape {
public Square() {
type = "Square";
}
@Override
public void draw() {
System.out.println("Inside Square::draw() method.");
}
}
// Prototype Registry
import java.util.Hashtable;
public class ShapeCache {
private static Hashtable shapeMap = new Hashtable<>();
public static Shape getShape(String shapeId) {
Shape cachedShape = shapeMap.get(shapeId);
return (Shape) cachedShape.clone();
}
// For each shape run database query and create shape
// shapeMap.put(shapeKey, shape);
public static void loadCache() {
Rectangle rectangle = new Rectangle();
rectangle.setId("1");
shapeMap.put(rectangle.getId(), rectangle);
Square square = new Square();
square.setId("2");
shapeMap.put(square.getId(), square);
}
}
Using the Prototype Pattern
public class PrototypePatternDemo {
public static void main(String[] args) {
ShapeCache.loadCache();
Shape clonedShape1 = (Shape) ShapeCache.getShape("1");
System.out.println("Shape : " + clonedShape1.getType());
clonedShape1.draw();
Shape clonedShape2 = (Shape) ShapeCache.getShape("2");
System.out.println("Shape : " + clonedShape2.getType());
clonedShape2.draw();
}
}
How it Works
The client requests a shape by ID from the ShapeCache. The cache returns a cloned copy of the original shape stored inside it. This process avoids creating new instances from scratch and improves performance.
Advantages of Prototype Pattern
- Reduces the cost of creating objects.
- Helps keep a registry of prototypes for easy cloning.
- Promotes flexibility in object creation.
Interview Tips
- Explain differences between shallow and deep cloning.
- Give scenarios when Prototype is more suitable than Factory.
- Discuss how the pattern helps in reducing the creation overhead in resource-intense objects.
- Be ready to code a prototype clone method implementation.
Summary
The Prototype Design Pattern is essential when object creation is expensive or complex. By copying existing objects, software achieves performance improvements and enhanced flexibility. Mastering this pattern equips developers to handle complex object lifecycles efficiently.
If you found this post useful, please share your feedback or questions in the comments. Follow for more Java design pattern tutorials and best practices!
Comments
Post a Comment