Prototype pattern
Encyclopedia
|
| Tutorials | Encyclopedia | Dictionary | Directory |
|
![]()
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 to:
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. 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.
ExamplesThe 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] C#
/*
* Base class for all prototypes
*/
public abstract class PrototypeBase : ICloneable {
// cloning the prototype into a new instance
public abstract object Clone();
// some usefull action
public abstract void Action();
}// class PrototypeBase
/*
* Place where prototypes are cloning
*/
public class PrototypeManager {
Dictionary<string, PrototypeBase> prototypes = new Dictionary<string,PrototypeBase>();
//
// manage prototype list
//
public void AddPrototype(string name, PrototypeBase prototype) {
prototypes[name] = prototype;
}// AddPrototype()
public void DelPrototype(string name) {
prototypes.Remove(name);
}// DelPrototype()
public void DropAllPrototypes() {
prototypes.Clear();
}// DropAllPrototypes()
//
// main function of class
//
public PrototypeBase GetCopy(string name) {
if (prototypes.ContainsKey(name))
return (PrototypeBase)prototypes[name].Clone(); else
return null;
}// GetCopy()
}// class PrototypeManager
/*
* Concrete Prototype First
*/
public class PrototypeFirst : PrototypeBase {
public List<string> manyStrings = new List<string>();
//
// cloning the prototype into a new instance
//
public override object Clone() {
// kind of a deep copy
PrototypeFirst newObj = new PrototypeFirst();
foreach(string str in manyStrings)
newObj.manyStrings.Add( String.Copy(str) );
return newObj;
}// Clone()
//
// usefull action
//
public override void Action() {
foreach (string str in manyStrings)
Console.WriteLine(str);
}// Action()
}// class PrototypeFirst
/*
* Concrete Prototype Second
*/
public class PrototypeSecond : PrototypeBase {
public int value = 0;
//
// cloning the prototype into a new instance
//
public override object Clone() {
PrototypeFirst newObj = (PrototypeFirst)this.MemberwiseClone();
return newObj;
}// Clone()
//
// usefull action
//
public override void Action() {
Console.WriteLine(value);
}// Action()
}// class PrototypeSecond
/* ------------------------------- */
/*
* Usage example
*/
public class Usage {
public void Foo() {
PrototypeManager manager = new PrototypeManager();
//
// Filling prototype list
//
PrototypeFirst first = new PrototypeFirst();
first.manyStrings.Add("String 1");
first.manyStrings.Add("String 2");
manager.AddPrototype("first", first);
PrototypeSecond second = new PrototypeSecond();
second.value = 10;
manager.AddPrototype("second", second);
//
// Getting copy by prototype
//
PrototypeBase foo1 = manager.GetCopy("first");
foo1.Action();
}// Foo()
}// class Usage
C++VB.netJava
/** Prototype Class **/
public class Cookie implements Cloneable {
public Object clone() {
try {
Cookie copy = (Cookie)super.clone();
//In an actual implementation of this pattern you might now change references to
//the expensive to produce parts from the copies that are held inside the prototype.
return copy;
}
catch(CloneNotSupportedException 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 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();
}
}
PythonCloning in PHPIn 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 the prototype pattern very easy to implement. See object cloning for more information. Rules of thumbSometimes 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 (creation through inheritance), but they can be implemented using Prototype (creation through delegation). (GoF, p95) 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 initialization. (GoF, p116) Designs that make heavy use of the Composite and Decorator patterns often can benefit from Prototype as well. (GoF, p126) 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 their initial 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. References
de:Prototyp (Entwurfsmuster) es:Prototype (patrón de diseño) fr:Prototype (patron de conception) ko:????? ?? it:Prototype pt:Prototype ru:???????? (?????? ??????????????) uk:???????? (?????? ????????????) zh:????
Source: Wikipedia | The above article is available under the GNU FDL. | Edit this article
|
|
top
©2008-2009 TutorGig.com. All Rights Reserved. Privacy Statement