Easy patterns: Prototype
This article is created in continuation of easy patterns series description and presents a Prototype pattern which solves the problem of new class instances creation at runtime, especially when it takes more time to manually instantiate new class than make a copy of existing one.
Creational patterns:
Prototype (this article)
Structural patterns:
Behavioral patterns:
The main essence
This pattern is really useful in cases when it’s cheaper to clone some existing instance than instantiate it from a class. This approach really helps when classes to instantiate are specified at run-time. Building hierarchy of factories that represents a hierarchy of products might have a huge cost, especially in cases when only a few combinations of state are possible for some concrete instance. So the Prototype pattern should be considered as a lightweight solution to get a copy of existing class instance.
This pattern includes only two main roles:
- Prototype — interface and implementation of class which can clone itself
- Client — creates a new instance by asking a Prototype to clone itself
So, whenever the system needs to get new class instance, it asks an internal Prototype method to clone itself and return a result.
Example of use
In example we will create a coffee instance based on Coffee class (Prototype). After that we will create another coffee instance (with clone method) and will add some milk to it. As a result we would get two separate coffee instances (for free, without any explicit instantiation).
Profit
A Prototype pattern has many common places with an Abstract Factory pattern. It hides a concrete product classes from the client, so client needs to know less product names.
Using this pattern leads to a great benefit that is usual for JavaScript environment — client can install and remove prototypes at run-time.
Using a Prototype pattern can decrease a number of classes that system needs. Cloning logic can define behavior through object composition, so it’s up to you how should look and behave a cloned instance.
Factory method pattern from the other hand tends to have a subclass hierarchy. The Prototype pattern just uses implemented clone method instead of asking a factory method to create a new object based on some subclass hierarchy. So, using a Prototype pattern you can avoid using subclass hierarchy at all.
Weak places
From the other hand each subclass of Prototype must implement the clone logic. Implementing clone method can be difficult when existing class internals doesn’t support copying or have a complicated nested structure.
Conclusion
This pattern can make life easier if it’s possible to implement clone logic easily. Especially in places where a heavy usage of Composite and Decorator patterns exists.
If you found this article helpful, please hit the 👏 button and feel free to comment below!