Prototype Design PatternBeginner
A prototype design pattern is a creational design pattern, that is used to clone an object from an already instantiated object Rather than instantiating a new object.
What is Prototype Design Pattern ?
A prototype design pattern is a creational design pattern, that is used to clone an object from an already instantiated object
Rather than instantiating a new object which might be heavy operation. we can have a prototype structure and have it clone itself rather than running all the complex object creation login
When to use Prototype Design Pattern ?
- When you want to create an object from copying another one.
- When your application hard wires all the object creation logic in the "new" expression, in this case this is considered as a bad practice.
- When the instances of the classes can have a "state" property or a "type" and they share a common structure but only differs in this state.
What is the difference between Prototype and Factory patterns ?
In a previous tutorial we discussed the Factory design pattern . The difference may not be clear. they both overlap slightly.
Factory design pattern is used to hide the creation logic of objects from the consumer application providing a ready to use instance.
Sometimes the creation and instantiation process is heavy and time consuming, in this case we can clone an already instantiated object and use it.
This is where the prototype comes in handy.
Prototype design pattern UML diagram
The Prototype classes implement a common interface which defines a Clone() method that will be used when there is a need to clone the object
How to implement Prototype design pattern ?
In this C# example , The prototype class implements the "ICloneable" interface, which defines the "Clone()" method.
the Clone() method returns a MemberwiseClone() which returns a shallow copy of the current object and cast it to the required type.
I this tutorial we discussed how a prototype design pattern can be useful when we have multiple objects only differ in a few properties but they follow the same structure. It's useful in this case to clone an already created object rather than instantiating again as the instantiation process might be heavy process.
The prototype classes implement a common interface "ICloneable" which defines a "Clone()" method and any prototype class has to provide it's implementation of this Clone method.