Design Patterns: Prototype

Posted by Monik, 12 October 2010.
Programming Code Design Design Patterns
Book summary
Summary on basis of the book ,,Design Patterns: Elements of Reusable Object-Oriented Software'', by Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides, Addison-Wesley, 1995.


class GraphicTool{
draw(){
...
Product p = this.prototype.clone();
p.draw();
...
}
}
We use it when we do not know the class' type (Product) to instatiate at compiliation time. In this way we avoid building a factory for each Product type. We can also use this pattern if we are going to use many instances of Product with similar state (as this way it is more convenient).

Consequences:
  • (+) the code in containing class is not application-specific, not bound to any specific product implementation
  • (+) adding/removing registered prototypes can be done at run-time
  • (+) adjusting the prototype by registering existing class as prototype instead of creating a new class each time
  • (+) the user can define the properties of the prototype at run-time - so he can define new objects without programming!
  • (+) requires less objects than Factory Method
  • (-) requires implementing the clone() method in all subclasses of the Product class; can be hard if some of these classes already exist, or if there are circular references
  • remember that many languages that suport cloning by default, suport only shallow cloning
Variations:
  • clients can use a dynamic set of prototypes (provided by a prototype manager)
  • client might initialize the newly cloned object either by existing setters, or by calling an initialize(...) method
  • (* for example Smalltalk and Objective C treat classes as prototypes by default)

Comments


Comments: