The prototype pattern is a pattern that seems more complicated than it really is. Practically, it is just a method to clone objects. Why would we need to clone objects when, these days, instantiating objects is not too costly in terms of performance? There are several situations in which it is required to clone objects that are already instantiated:
- When the creation of a new object relies on an external resource or a hardware-intensive operation
- When we need a copy of the same object with the same state without having to redo all of the operations to get to that state
- When we need an instance of an object without knowing to which concrete class it belongs
Let's look at the following class diagram:
In the prototype pattern, the following classes are involved:
Prototype
: This is the base class, or an interface that declares theclone()
method that derived objects have to implement. In a simple scenario, we may not have a base class, and a direct concrete class is sufficient.ConcretePrototype...