|
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. ...
Structure The class diagram is as shown below: Hierarchy of UML 2. ...
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 Creational: Abstract factory • Builder • Factory • Prototype • Singleton Erich Gamma is a co-author of the influential computer science textbook, Design Patterns. ...
Richard Helm is currently with The Boston Consulting Group where he consults on the strategic application of technology to business. ...
This article is about the book by Gamma et al. ...
{{Hide = {{{ Hybrid reference style allows grouped references at top, but uses m:Cite. ...
This article is about the book by Gamma et al. ...
A software design pattern, the Abstract Factory Pattern provides a way to encapsulate a group of individual factories that have a common theme. ...
Oftentimes, builder pattern builds Composite pattern, a structure pattern. ...
The Factory Method pattern is an object-oriented design pattern. ...
In software engineering, the singleton design pattern is used to restrict instantiation of a class to one object. ...
Structural: Adapter • Bridge • Composite • Decorator • Façade • Flyweight • Proxy In computer programming, the adapter design pattern (sometimes referred to as the wrapper pattern or simply a wrapper) adapts one interface for a class into one that a client expects. ...
The bridge pattern is a design pattern used in software engineering which is meant to decouple an abstraction from its implementation so that the two can vary independently (Gamma et. ...
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 façade pattern is an object-oriented design pattern. ...
Flyweight is a software design pattern. ...
// In computer programming, the proxy pattern is a software design pattern. ...
Behavorial: Chain of responsibility • Command • Interpreter • Iterator • Mediator • Memento • Observer • State • Strategy • Template method • Visitor In computer programming, the chain-of-responsibility pattern is a design pattern consisting of a source of command objects and a series of processing objects. ...
In object-oriented programming, the Command pattern is a design pattern in which objects are used to represent actions. ...
In computer programming, the interpreter pattern is a particular design pattern. ...
In object-oriented programming, an iterator is an object allowing one to sequence through all of the elements or parts contained in some other object, typically a container or list. ...
The mediator pattern is a software design pattern that provides a unified interface to a set of interfaces in a subsystem. ...
The memento pattern is a software design pattern that provides the ability to restore an object to its previous state (undo by rollback). ...
// The observer pattern (sometimes known as publish/subscribe) is a design pattern used in computer programming to observe the state of an object in a program. ...
A behavioral software design pattern, state pattern is used in computer programming to represent the state of an object. ...
In computer programming, the strategy pattern is a particular software design pattern, whereby algorithms can be selected on-the-fly at runtime. ...
Template method: UML class diagram. ...
In object-oriented programming and software engineering, the visitor design pattern is a way of separating an algorithm from an object structure. ...
|