Design Pattern ->Prototype

Layering & Contract Philosophy With additional indirection

Prototype

The example code is as following:

 1 class CObject
 2 {
 3    public: 
 4              virtual CObject* clone() const = 0;
 5              virtual void BasicOperation() = 0;
 6 }
 7 //clone is a virtual method, its return type can be different from base class
 8 class CConcreteObject: public CObject
 9 {
10     public: 
11       virtual CConcreteObject* clone() const { return new CConcreteObject (*this);}
12 }
13 
14 class Client
15 {
16     public: CObject* pObject = NULL;
17     public: 
18     void setObject(CObject *p) 
19     { 
20        if (pObject != NULL ) 
21           delete pObject; 
22        pObject = NULL; 
23        pObject = p->clone();
24     }
25     void operation() { pObject->BasicOperation();}
26 }

Applicability

  • Use the Prototype pattern when:a system should be independent of how its products are created, composed, and represented;
  • Use the Prototype pattern when: the classes to instantiate are specified at run-time, for example, by dynamic loading; or to avoid building a class hierarchy of factories that parallels the class hierarchy of products; or when instances of a class can have one of only a few different combinations of state. It may be more convenient to install a corresponding number of prototypes and clone them rather than instantiating the class manually,each time with the appropriate state.

Participants

  • Prototype (Graphic): declares an interface for cloning itself which must be implemented by derived class.
  • ConcretePrototype (Staff, WholeNote, HalfNote): implements an operation for cloning itself.
  • Client (GraphicTool): creates a new object by asking a prototype to clone itself.

Collaborations

  • A client asks a prototype to clone itself and manipulates them as own.

 From:Design Patterns:Elements of Reusable Object-Oriented Software, by GoF

原文地址:https://www.cnblogs.com/iiiDragon/p/3224357.html