Prototype Pattern Code Review
Define the Prototype Interface and Handler Objects
Code Download
- Download Description:prototype pattern download
- .NET Framework:3.5
- .NET Language:C#
- Date Published:2009-07-01
- Download Size:9 KB
Code Review
- Prototype Pattern Code Review: Define the Prototype Interface and Handler Objects
- Prototype Pattern Code Review: Define the PrototypeManager Object
- Prototype Pattern Code Review: Use the Prototype Pattern
Code Walkthrough
Define the IPrototype abstract to be used as the base class for the main Prototype classes.
public ProtoType DeepCopy() { MemoryStream stream = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, this); stream.Seek(0, SeekOrigin.Begin); ProtoType copy = (ProtoType)formatter.Deserialize(stream); stream.Close(); return (copy); } }
The class defines the Clone() method (which does a shallow copy of the original object) and the DeepCopy() method.
A shallow copy creates a new instance of the same type as the original object, and then copies the nonstatic fields of the original object. If the field is a value type, a bit-by-bit copy of the field is performed. If the field is a reference type, the reference is copied but the referred object is not; therefore, the reference in the original object and the reference in the clone point to the same object.
In contrast, a deep copy of an object duplicates everything directly or indirectly referenced by the fields in the object.
The ProtoType class (object) represents the original prototype class, from which other classes will be cloned.
public ProtoType(String country, String capital, String language) { this.Country = country; this.Capital = capital; this.Language = new DeeperData(language); }
public override string ToString() { return(String.Format("{0}\t\t{1}\t\t->{2}", this.Country, this.Capital, this.Language)); } }
The DeeperData class (object) is an extension to the Prototype class (object) and represents a referred object in the Prototype class (object).
public DeeperData(String s) { this.Data = s; }
public override string ToString() { return (Data); } }
Printer Friendly Version
Add to Favourites
DotNet Kicks
Digg
del.icio.us
Live Favourites
ma.gnolia
reddit
Slashdot
Technorati
Yahoo!