- Is a Creational Pattern.
- This design pattern that is used to instantiate a class by copying, or cloning, the properties of an existing object.
- The new object is an exact copy of the prototype but permits modification without altering the original.
- Cloning can be achieved by implementing ICloneable of the System namespace.
- The only member of ICloneable interface is Clone method that returns a new instance of a class with the same value as an existing instance.
- C# ICloneable.Clone method signature is: object Clone();
- Duplicates all of the object’s properties.
- In case a reference type, the reference is copied.
- This means that changes to the referenced object are visible in both the clone and the original object.
- Clones the main object and all child objects.
- Reference types are also cloned, giving a truly independent copy.
- The prototype pattern usually generates deep copies, though this is dependent upon the situation.
Why & When
- When we want the new copy object changes should not affect the old object.
- When the construction of a brand new object, using the new operator, is inefficient.
- Generally used for complex classes or for classes those are costly to instantiate.
- When we need to hide the concrete product classes from the client.
- When we want to reduce the number of classes to the minimum.
- When we use dynamic loading.
- When we want to avoid using the complicated class hierarchy of factories.
- When the classes have a few different state combinations.
- Session replication from one server to another server
In an enterprise-level application managing a server pool, the application will monitor and maintain the optimum load on the individual server in the pool. In case of the catastrophic failure, one server may invalidate thousands of client connections. The enterprise application managing the server pool can take the responsibility of cloning the sessions from one server to another without disturbing the clients.
- Generating the GUI having many numbers of similar controls
This is a quite frequent scenario. One can have a form or GUI that hosts many similar controls. In order to maintain the consistency, one needs to initialize every object to the same standard state. This process of initialization gets repeated again and again for each control increasing the number of lines of code. In order to optimize this part of the code, one can one have an object of a control initialized to a standard state and then replicate the same object to create as many controls needed.
- Creates deep copy of the complex object hierarchy
- Reduced load of initialization
- Reusability – Optimized coding efforts
- Simplified object copy process
How to Achieve
— Abstract Parent Class
–– Child Class
— Using Child Class