Pattern Name:
Prototype Pattern
Clone or copy initialized instances
Usage:
Easy pattern, usage depends on the preferred software design, provides an alternative to the other creational patterns that are mainly based on external classes for creation
1 / 5
UML Class Diagram:
Explanation:
- The abstract prototype class defines the interface that contains a clone method for cloning itself.
- The inherited classes implement the clone function. Note that C# provides two different ways of cloning an object: by shallow copy (only top level objects) or by deep copy (all objects).
- You could also manually create a new object and set its values with the values of the original object but since C# already implements everything necessary I advise using that.
- The client class does not create new objects itself. Instead it asks the objects to clone themselves when needed. The cloned objects are perfect copies and contain all values of the original objects depending on the shallow or deep copy approach (see above).
- You may also use the ICloneable interface that already exists in C#
- In the last step we add some code to test the software design and the Prototype implementation.
- When running the example you can see that everything is working as expected and that the correct classes are instantiated during runtime.
Source Code:
http://csharpdesignpatterns.codeplex.com/
No comments:
Post a Comment