FACTOID # 10: Indians go out to the movies 3 billion times a year - much more than any other nation.
 
 Home   Encyclopedia   Statistics   Countries A-Z   Flags   Maps   Education   Forum   FAQ   About 
 
WHAT'S NEW
RECENT ARTICLES
More Recent Articles »
 

Encyclopedia > Prototype pattern

A prototype pattern is a creational design pattern used in software development when the type of objects to create is determined by a prototypical instance, which is cloned to produce new objects. This pattern is used for example when the inherent cost of creating a new object in the standard way (e.g., using the 'new' keyword) is prohibitively expensive for a given application. {{Hide = {{{ Hybrid reference style allows grouped references at top, but uses m:Cite. ...


To implement the pattern, declare an abstract base class that specifies a pure virtual clone() method. Any class that needs a "polymorphic constructor" capability derives itself from the abstract base class, and implements the clone() operation. In computing, a pure virtual method is one which has a declaration (a signature), but no definition (implementation). ... In computer science, polymorphism means allowing a single definition to be used with different types of data (specifically, different classes of objects). ... In object-oriented programming, a constructor (sometimes shorted to ctor) in a class is a special block of statements called when an object is created, either when it is declared (statically constructed on the stack, possible in C++ but not in Java and other object-oriented languages) or dynamically constructed... In computer science, a superclass is a class from which other classes are derived. ...


The client, instead of writing code that invokes the "new" operator on a hard-wired class name, calls the clone() method on the prototype, calls a factory method with a parameter designating the particular concrete derived class desired, or invokes the clone() method through some mechanism provided by another design pattern. A Factory method is a static method of a class that constructs another instance of an object. ...

Contents

Structure

The class diagram is as shown below: Hierarchy of UML 2. ...


Image:Prototype classdia.png Image File history File links Prototype_classdia. ...


C# sample code

 public enum RecordType { Car, Person } /// <summary> /// Record is the Prototype /// </summary> public abstract class Record { public abstract Record Clone(); } /// <summary> /// PersonRecord is the Concrete Prototype /// </summary> public class PersonRecord : Record { string name; int age; public override Record Clone() { return (Record)this.MemberwiseClone(); // default deep copy } } /// <summary> /// CarRecord is another Concrete Prototype /// </summary> public class CarRecord : Record { string carname; Guid id; public override Record Clone() { CarRecord clone = (CarRecord)this.MemberwiseClone(); // default deep copy clone.id = Guid.NewGuid(); // always generate new id return clone; } } /// <summary> /// RecordFactory is the client /// </summary> public class RecordFactory { private static Dictionary<RecordType, Record> _prototypes = new Dictionary<RecordType, Record>(); /// <summary> /// Constructor /// </summary> public RecordFactory() { _prototypes.Add(RecordType.Car, new CarRecord()); _prototypes.Add(RecordType.Person, new PersonRecord()); } /// <summary> /// The Factory method /// </summary> public Record CreateRecord(RecordType type) { return _prototypes[type].Clone(); } } 

Java sample code

 /** Prototype Class **/ public class Cookie implements Cloneable { public Object clone() { try{ //In an actual implementation of this pattern you would now attach references to //the expensive to produce parts from the copies that are held inside the prototype. return this.getClass().newInstance(); } catch(InstantiationException e) { e.printStackTrace(); return null; } } } /** Concrete Prototypes to clone **/ public class CoconutCookie extends Cookie { } /** Client Class**/ public class CookieMachine { private Cookie cookie;//could have been a private Cloneable cookie; public CookieMachine(Cookie cookie) { this.cookie = cookie; } public Cookie makeCookie() { return (Cookie)cookie.clone(); } public Object clone() { } public static void main(String args[]){ Cookie tempCookie = null; Cookie prot = new CoconutCookie(); CookieMachine cm = new CookieMachine(prot); for(int i=0; i<100; i++) tempCookie = cm.makeCookie(); } } 

Examples

The Prototype pattern specifies the kind of objects to create using a prototypical instance. Prototypes of new products are often built prior to full production, but in this example, the prototype is passive and does not participate in copying itself. The mitotic division of a cell - resulting in two identical cells - is an example of a prototype that plays an active role in copying itself and thus, demonstrates the Prototype pattern. When a cell splits, two cells of identical genotype result. In other words, the cell clones itself. [Michael Duell, "Non-software examples of software design patterns", Object Magazine, Jul 97, p54]


Rules of thumb

Sometimes creational patterns overlap - there are cases when either Prototype or Abstract Factory would be appropriate. At other times they complement each other: Abstract Factory might store a set of Prototypes from which to clone and return product objects (GoF, p126). Abstract Factory, Builder, and Prototype can use Singleton in their implementations. (GoF, p81, 134). Abstract Factory classes are often implemented with Factory Methods, but they can be implemented using Prototype. (GoF, p95) In software engineering, creational design patterns are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. ... A software design pattern, the Abstract Factory Pattern provides a way to encapsulate a group of individual factories that have a common theme. ... Design Patterns (ISBN 0201633612) is a computer science book proposing standard solutions and naming conventions to common problems in software design. ... Oftentimes, builder pattern builds Composite pattern, a structure pattern. ... In software engineering, the singleton design pattern is used to restrict instantiation of a class to one object. ...


Factory Method: creation through inheritance.
Prototype: creation through delegation. In object-oriented programming, inheritance is a way to form new classes (instances of which are called objects) using classes that have already been defined. ... In object-oriented programming there are two notions of delegation. ...


Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed. (GoF, p136)


Prototype doesn't require subclassing, but it does require an "initialize" operation. Factory Method requires subclassing, but doesn't require Initialize. (GoF, p116)


Designs that make heavy use of the Composite and Decorator patterns often can benefit from Prototype as well. (GoF, p126) This article needs to be cleaned up to conform to a higher standard of quality. ... In object-oriented programming, a decorator pattern is a design pattern. ...


The rule of thumb could be that you would need to clone() an Object when you want to create another Object at runtime which is a true copy of the Object you are cloning. True copy means all the attributes of the newly created Object should be the same as the Object you are cloning. If you could have instantiated the class by using new instead, you would get an Object with all attributes as thier intial values. For example, if you are designing a system for performing bank account transactions, then you would want to make a copy of the Object which holds your account information, perform transactions on it, and then replace the original Object with the modified one. In such cases, you would want to use clone() instead of new.


Cloning in PHP

In PHP 5, unlike previous versions, objects are by default passed by reference. In order to pass by value, use the "magic function" __clone(). This makes using the prototype pattern very easy to implement. See object cloning for more information. PHP (PHP: Hypertext Preprocessor) is a reflective programming language originally designed for producing dynamic Web pages. ...


References


  Results from FactBites:
 
Design Pattern Synopses (4381 words)
The Filter pattern is a special case of the Decorator pattern, where a data source or data sink object is wrapped to add logic to the handling of a data stream.
The Composite pattern also allows the objects in the tree to be manipulated in a consistent manner, by requiring all of the objects in the tree to have a common superclass or interface.
The Flyweight pattern is often combined with the Composite pattern to represent the leaf nodes of a hierarchical structure with shared objects.
  More results at FactBites »

 

COMMENTARY     


Share your thoughts, questions and commentary here
Your name
Your location
Your comments
Please enter the 5-letter protection code


Lesson Plans | Student Area | Student FAQ | Reviews | Press Releases |  Feeds | Contact
The Wikipedia article included on this page is licensed under the GFDL.
Images may be subject to relevant owners' copyright.
All other elements are (c) copyright NationMaster.com 2003-5. All Rights Reserved.
Usage implies agreement with terms.