The prototype pattern is used to instantiate a new object by copying all of the properties of an existing object, creating an independent clone. This practise is particularly useful when the construction of a new object is inefficient.
Imagine, we have a SmartPhone class as bellow:
Now we need to create 5 instances of this class look like this:
We can easy to realize that many instances have the same properties so we often duplicate the code line then edit any properties differently. It’s okay but not optimized & easy to make mistakes. Let’s try to apply the Prototype pattern into SmartPhone class as bellow:
We declare a clone func with default optional parameters are the same with properties. This func returns a new instance by copying all of the properties of an existing instance then modifies some properties if needed. Now create 5 intances as bellow:
We don’t need to initialize a new instance by calling the designed initializer anymore, just “clone” the current instance then modify it!
That’s all! Prototype pattern is very simple to understand & easy to implement by other programming languages as well. It’s particularly useful when the construction of a new object is inefficient. Leave your commend if you have any concerns, thanks for reading!