Prototype pattern
From Wikipedia, the free encyclopedia
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:
- avoid subclasses of an object creator in the client application, like the abstract factory pattern does.
- avoid the inherent cost of creating a new object in the standard way (e.g., using the 'new' keyword) when it is prohibitively expensive for a given application.
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.
Contents |
[edit] Structure
The class diagram is as shown below: (the arrow from Client to Prototype should not be a triangle, but a classical arrow ->) (Prototype should be abstract)
[edit] C++ Sample code
#include <iostream> #include <map> #include <string> #include <cstdint> using namespace std; enum RECORD_TYPE_en { CAR, BIKE, PERSON }; /** * Record is the Prototype */ class Record { public : Record() {} virtual ~Record() {} virtual Record* Clone() const=0; virtual void Print() const=0; }; /** * CarRecord is Concrete Prototype */ class CarRecord : public Record { private : string m_oStrCarName; uint32_t m_ui32ID; public : CarRecord(const string& _oStrCarName, uint32_t _ui32ID) : Record(), m_oStrCarName(_oStrCarName), m_ui32ID(_ui32ID) { } CarRecord(const CarRecord& _oCarRecord) : Record() { m_oStrCarName = _oCarRecord.m_oStrCarName; m_ui32ID = _oCarRecord.m_ui32ID; } ~CarRecord() {} CarRecord* Clone() const { return new CarRecord(*this); } void Print() const { cout << "Car Record" << endl << "Name : " << m_oStrCarName << endl << "Number: " << m_ui32ID << endl << endl; } }; /** * BikeRecord is the Concrete Prototype */ class BikeRecord : public Record { private : string m_oStrBikeName; uint32_t m_ui32ID; public : BikeRecord(const string& _oStrBikeName, uint32_t _ui32ID) : Record(), m_oStrBikeName(_oStrBikeName), m_ui32ID(_ui32ID) { } BikeRecord(const BikeRecord& _oBikeRecord) : Record() { m_oStrBikeName = _oBikeRecord.m_oStrBikeName; m_ui32ID = _oBikeRecord.m_ui32ID; } ~BikeRecord() {} BikeRecord* Clone() const { return new BikeRecord(*this); } void Print() const { cout << "Bike Record" << endl << "Name : " << m_oStrBikeName << endl << "Number: " << m_ui32ID << endl << endl; } }; /** * PersonRecord is the Concrete Prototype */ class PersonRecord : public Record { private : string m_oStrPersonName; uint32_t m_ui32Age; public : PersonRecord(const string& _oStrPersonName, uint32_t _ui32Age) : Record(), m_oStrPersonName(_oStrPersonName), m_ui32Age(_ui32Age) { } PersonRecord(const PersonRecord& _oPersonRecord) : Record() { m_oStrPersonName = _oPersonRecord.m_oStrPersonName; m_ui32Age = _oPersonRecord.m_ui32Age; } ~PersonRecord() {} Record* Clone() const { return new PersonRecord(*this); } void Print() const { cout << "Person Record" << endl << "Name : " << m_oStrPersonName << endl << "Age : " << m_ui32Age << endl << endl ; } }; /** * RecordFactory is the client */ class RecordFactory { private : map<RECORD_TYPE_en, Record* > m_oMapRecordReference; public : RecordFactory() { m_oMapRecordReference[CAR] = new CarRecord("Ferrari", 5050); m_oMapRecordReference[BIKE] = new BikeRecord("Yamaha", 2525); m_oMapRecordReference[PERSON] = new PersonRecord("Tom", 25); } ~RecordFactory() { delete m_oMapRecordReference[CAR]; delete m_oMapRecordReference[BIKE]; delete m_oMapRecordReference[PERSON]; } Record* CreateRecord(RECORD_TYPE_en enType) { return m_oMapRecordReference[enType]->Clone(); } }; int main() { RecordFactory* poRecordFactory = new RecordFactory(); Record* poRecord; poRecord = poRecordFactory->CreateRecord(CAR); poRecord->Print(); delete poRecord; poRecord = poRecordFactory->CreateRecord(BIKE); poRecord->Print(); delete poRecord; poRecord = poRecordFactory->CreateRecord(PERSON); poRecord->Print(); delete poRecord; delete poRecordFactory; return 0; }
[edit] 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 shallow copy } } /// <summary> /// CarRecord is another Concrete Prototype /// </summary> public class CarRecord : Record { string carname; Guid id; public override Record Clone() { CarRecord clone = (Record)this.MemberwiseClone(); // default shallow 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(); } }
[edit] Java sample code
/** 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 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(); } }
[edit] 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]
[edit] 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 (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.
[edit] 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.
[edit] References
- Gamma, Erich; Helm, Richard; Johnson, Ralph; Vlissides, John (1994). Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley. ISBN 0-201-63361-2.
|