Prototype Pattern
Introduction:
Prototype design pattern is a creational design pattern. It allows us to create a copy of the existing object without creating the new instance.
How do we create a copy of the object? We create new object of the same class and start copying each field. But this direct approach has some issues. If the class has private fields, that can't be copied from outside of that class, also if we working with abstract class, we don't know about the concrete implementation.
This pattern delegates the cloning process to the actual object that is being cloned. This pattern provides the common interface "clone" to all the cloning object. The object which supports cloning process called prototype. The object which supports cloning process implements 'clone' method and creates its own copy.
When to use,
- When your code shouldn’t depend on the concrete classes of objects that you need to copy.
- When your code shouldn’t depend on the concrete classes of objects that you need to copy.
- When creating object is an expensive process.
How to use,
- Create prototype abstract class with clone() method.
- Implement the clone() method in the class which supports cloning process.
- Create a factory class which has the registry of prototype objects.
- Design a factory method that: may (or may not) accept arguments, finds the correct prototype object, calls
clone()
on that object, and returns the result. - The client replaces all references to the
new
operator with calls to the factory method.