0

Prototype Pattern

Clone or duplicate an object after costly DB operation or other costly operation. Put clone object into a HashMap.

Example: Example – Costly DB Operation, Hash Mapping

Suppose we are doing a sales analysis on a set of data from a database. Normally, we would copy the information from the database, encapsulate it into an object and do the analysis. But if another analysis is needed on the same set of data, reading the database again and creating a new object is not the best idea. If we are using the Prototype pattern then the object used in the first analysis will be cloned and used for the other analysis.

Source Code (Java):

public abstract class Shape implements Cloneable {

	private int id;
	private int type;

	public abstract void display();

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public int getType() {
		return type;
	}

	public void setType(int type) {
		this.type = type;
	}

	@Override
	protected Object clone() throws CloneNotSupportedException {
		// TODO Auto-generated method stub
		return super.clone();
	}

}
public class ShapeMapper {

	private static Hashtable<Integer, Shape> shapeMap = new Hashtable<>();

	public static Shape getShape(int id) throws CloneNotSupportedException {
		Shape shape = shapeMap.get(id);
		return (Shape) shape.clone();
	}

	public static void loadShape() {

		Circle circle = new Circle();
		circle.setId(1);
		circle.setType(1);
		shapeMap.put(circle.getId(), circle);

		Rectenagle rectenagle = new Rectenagle();
		rectenagle.setId(2);
		rectenagle.setType(2);
		shapeMap.put(rectenagle.getId(), rectenagle);
	}

}
public class MainClass {
	public static void main(String[] args) {

ShapeMapper.loadShape();
		Shape shape = ShapeMapper.getShape(1);
		shape.display();
		System.out.println("Shape Type" + shape.getType());
		Shape shape2 = ShapeMapper.getShape(2);
		shape2.display();
		System.out.println("Shape Type" + shape2.getType());
	}
}

Toufiq Mahmud

Leave a Reply

Your email address will not be published.