Wednesday, 30 October 2019

Prototype Design Pattern

Question: What is a prototype object creational pattern? 
Answer: You simple store a map of String & Object. And whenever you need an Object of a particular type(specified by string key), you simply make the copy of the prototype object your have stored earlier while creating the registry. 

Components:

1. Prototype registry: In this class you create a Map<String,Object> of Key and Prototype Object. and you ask this registry to give an object via a public api. When the api is called, it simply calls copies the prototype object. Simple way is to just call clone() method of java to deep copy. All objects in this pattern must be implementing Cloneable interface. 

2. Client: Asks the registry to get the object.

Question: When to use?
Answer: When Object creation is expensive than copying. When you have a log of objects with very few state variables. You can opt to just clone() them than creating new objects. 

No comments:

Post a Comment