Prototype - Harsh4999/Design-Patterns GitHub Wiki
Use
- Whenever we want to ignore creation of object of some type in order to save cost or memory or some performance we use prototype.
- They help us create copies of existing instance and saves us from recreating the objects from scratch
Uml
- Prototype Abstract is a class whos object will serve as prototype of our use.
- Prototype has a method clone
- Concrete Prototype will be used to override the clone method as per needs
- Client/Director will use prototypes to clone the classes
Implementation
- We start by creating a class which will be a prototype (indicate that cloning is supported)
- Class must implement cloneable interface
- Clss should have override clone method and return a copy of itself
- Method should declare CloneNotSupportedException in throws to give subclasses a chance to decide on whether to support clonning or not
- While implementing Clone method we should consider the deep copy & shallow copy and choose which ever is applicable
- We also need to implement initialize method in the prototype class
- If the object which we are cloning is immutable use shallow copy else deep copy
- We should always provide reset method to reset cloned state
- Its usefull when we have a large object
- Prototype registry is a class in which we can register the main instance of the prototype and later on from registry we can clone the prototype
- Eg: Object.clone()
- Example code here