7/30/2011

Design Pattern - Prototype

Definition
Specify the kind of objects to create using a prototypical instance, and create new objects by copying this prototype (create object by clone from prototype).

UML Class Diagram


Notes
- The .NET optimized code demonstrates the same functionality as the real-world example but uses more modern, built-in .NET features. The abstract classes have been replaced by interfaces because the abstract classes contain no implementation code.

- ICloneable is a built-in .NET prototype interface. ICloneable requires that the class hierarchy be serializable. Here the Serializable attribute is used to do just that (as an aside: if a class has 'event' members then these must be decorated with the NonSerialized attribute). Alternatively, reflection could have been used to query each member in the ICloneable class. Tip: always be concerned about poor performance when implementing cloning many objects through serialization or reflection.

Prototype: when and where use it 
- Like other creational patterns (Builder, Abstract Factory, and Factory Method), the Prototype design pattern hides object creation from the client. However, instead of creating a non-initialized object, it returns a new object that is initialized with values it copied from a prototype - or sample - object. The Prototype design pattern is not commonly used in the construction of business applications. It is more often used in specific application types, such as, computer graphics, CAD (Computer Assisted Drawing), GIS (Geographic Information Systems), and computer games. 

- The Prototype design pattern creates clones of pre-existing sample objects. The best way to implement this in .NET is to use the built-in ICloneable interface on the objects that are used as prototypes. The ICloneable interface has a method called Clone that returns an object that is a copy, or clone, of the original object.  

- When implementing the Clone functionality you need to be aware of the two different types of cloning: deep copy versus shallow copy.  Shallow copy is easier but only copies data fields in the object itself -- not the objects the prototype refers to.  Deep copy copies the prototype object and all the objects it refers to.  Shallow copy is easy to implement because the Object base class has a MemberwiseClone method that returns a shallow copy of the object.  The copy strategy for deep copy may be more complicated -- some objects are not readily copied (such as Threads, Database connections, etc). You also need to watch out for circular references.  

Sample
- Create Product class implement ICloneable interface.

- Create Factory class to create prototype.

- Create instance of Product using Factory.

Ref: Gang of Four tutorial

No comments:

Post a Comment