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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值