zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    【数学】【AOJ-614】座位安排
    【乱搞】【AOJ-611】消失的5,8,9
    redis 与session
    Nginx 与 tomcat 部署网站
    linux 进程在后台执行
    印象笔记
    consul 小結
    spring boot 使用拦截器,注解 实现 权限过滤
    Springcloud/Springboot项目绑定域名,使用Nginx配置Https
    spring boot 登录认证
  • 原文地址:https://www.cnblogs.com/iiiDragon/p/3224357.html
Copyright © 2011-2022 走看看