2007 |
Section 4, Chapter 2 |
Prototype Pattern
Concept
The Prototype pattern gives us a way to produce a copy or clone of a class that we already have created and configured. Prototype method is internal to the originating class, and has access to its class's internal variables. This gives the method direct access to both the originating and the new class's internal state. This allows us to capture the present state of the original object in its clone so we can modify the cloned object without introducing those changes to the original.
Use
Creating a new class from scratch would not reproduce the appropriate internal variable values in the new class we desired without violating rules of encapsulation of the class. Simply constructing a new class would not get us the class in its current state. Making a clone of the existing class would allow the clone to be modified and used without changing the original and would allow us to capture the originating class's state in the new class.
Or we cannot create a new class in the current scope of the code or because allowing a constructor on the class in the current scope violates the rules of encapsulation of our application. We could not call the constructor because of its encapsulation properties.
Design
The Prototype pattern has one main component: the Prototype. The prototype is really an ordinary class that has a method implemented to create a copy (or clone) of itself.
Illustration
abstract class Stone
{
public abstract Stone Clone();
}
class Granite : Stone
{
public override Stone Clone()
{
return (Granite)this.MemberwiseClone();
}
}
Stone clonedStone = stone.Clone();
Note: The .NET MemberwiseClone() method only provides a shallow copy of the class, below provides a solution of deep cloning. |
public override Stone Clone()
{
Stone ret = (Granite)this.MemberwiseClone();
foreach(object obj in _collection)
ret.Add(obj.Clone()); //Reference Type is also cloned
return ret;
}
December 2007 |
Section 1, Chapter 5 |
Vincent's Demonstration