Saturday, May 7, 2011

[Tutorial] Common Design Patterns in C# 4.0
Part5: Prototype Pattern

Pattern Name:
Prototype Pattern

Short Description:
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

Complexity:
1 / 5

UML Class Diagram:

image

Explanation:

  • The abstract prototype class defines the interface that contains a clone method for cloning itself.

image

  • 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.

image

  • 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).

image

  • You may also use the ICloneable interface that already exists in C#

image

  • In the last step we add some code to test the software design and the Prototype implementation.

image

  • When running the example you can see that everything is working as expected and that the correct classes are instantiated during runtime.

image

Source Code:
http://csharpdesignpatterns.codeplex.com/


Share/Save/Bookmark

No comments: