Prototype Design Pattern in C# with Examples
Gang of Four Definition : "Prototype Design Pattern Specify the kind of objects to create using a prototypical instance, and create new objects by copying this prototype"
To simplify, instead of creating object from scratch every time, you can make copies of an original instance and modify it as required.
Prototype is unique among the other creational patterns as it doesn't require a class but only an end object.
We need to choose Prototype Design Pattern when
The cloning falls under two categories: shallow and deep.
This concludes the post about the Prototype Design Pattern and I hope you found this post helpful. Thanks for visiting, Cheers!!!
- Creating an object is an expensive operation and it would be more efficient to copy an object.
- System should be independent of how its products are created, composed, and represented.
- Objects are required that are similar to existing objects.
- We need to hide the complexity of creating new instance from the client.
Prototype Representation
Shallow and Deep Copy : The idea of using copy is to create a new object of the same type without knowing the exact type of the object we are invoking.
Shallow Copy : copies an object's value type fields into the target object and the object's reference types are copied as references into the target object.
Shallow Copy : copies an object's value type fields into the target object and the object's reference types are copied as references into the target object.
Deep Copy : Deep Copy copies an object's value and reference types into a complete new copy of the target objects.
Difference between Shadow and Deep Cloning
The cloning falls under two categories: shallow and deep.
- A shallow copy copies all reference types or value types, but it does not copy the objects that the references refer to. The references in the new object point to the same objects that the references in the original object points to.
(Only Parent Object is cloned here).
- In contrast, a deep copy of an object copies the elements and everything directly or indirectly referenced by the elements.
(Parent Object is cloned along with the containing objects)
Prototype Design Pattern C# Implementation
Let us create a C# application to implement the pattern, here in this sample application we are going to use the shallow copy mechanism. The application uses the inbuild ICloneable interface provided by the .NET Framework.
|
This concludes the post about the Prototype Design Pattern and I hope you found this post helpful. Thanks for visiting, Cheers!!!
EmoticonEmoticon