Prototype Pattern
GoF
: Specify the kinds of objects to create using a protypical instance, and create new objects by copying this prototypeWiki
:Other
: creates copy of objects that are very expensive to create
Concepts
- Avoids costly creation
- Avoids Subclassing
- Typically doesn't use keyword "new"
- Often utilizes an Interface
- Usually implemented with a registry
- Example:
- java.lang.Object#clone()
Design considerations
- Typically implements clone/cloneable
- Avoids keyword "new"
- Although copy, each instance is unique
- Costly construction not handled by client (builder is opposite of prototype)
- Can still utilize parameters for construction
- Shallow vs deep copy design considerations can be made
Example/Demo
- Create Prototype
- Demonstrate shallow copy
- Create with a registry
Note:
- We have seen an example with
clone()
method, but this can also be achieved by creatin an interface and implementing the clone method. - You can replace string with enum in createItem method of registry.
Drawbacks
- Sometimes not clear when to use
- Used with other patterns
- Registry
- Mostly shallow copy by clone, for deep copy we have to implement ourselves and it requires a lot of code
Contrast to other patterns
Prototype | Factory |
---|---|
Light weight construction | Flexible Objects based on request |
- Copy constructor or clone method | - multiple constructors can be use instead of just clone method |
Choose shallow vs deep copy | Create fresh and cconcrete instance of object |
Main purpose to create copy of itself | NA |
Summary
- Guarantee unique instance
- Often refactored in
- Can help with performance issues
- Dont always jump to a factory
Prototype patterns are usually implemented with a Registry
A Prototype is used when you want to guarantee a unique instance that is lightweight to create
Next:
you can try prototype pattern with Generics and without clone method References: https://refactoring.guru/design-patterns/prototype