原型模式Prototype(c++设计模式)

面试官:请你谈谈原型模式


原型模式使用原型示例指定待创建对象的类型,并且 通过复制这个原型来创建新的对象

模式优点

  • 简化对象的创建过程
  • 扩展性好
  • 提供了简单的创建结构
  • 可以用深克隆的方式保存对象的状态

模式缺点

  • 需要为每一个类配备一个克隆方法,而且该方法位于一个类的内部,当对已有的类进行改造时,需要修改源代码,违背开闭原则
  • 在实现深克隆时需要编写较为复杂的代码

适用环境

  • 创建新对象陈本较大
  • 系统要保存对象状态,而对象的状态变化很小
  • 需要避免使用分层次的工厂类来创建对象
  • Ctrl+C、Ctrl+V

原型模式代码

/*
 * @ Description: C++ Design Patterns___Prototype
 * @ version: v1.0
 * @ Author: WeissxJ
 */
#include<iostream>
#include<string>

class Prototype
{
    public:
        virtual ~Prototype() {}

        virtual Prototype* clone()=0;
        virtual std::string type()=0;
        // ...
};

class ConcretePrototypeA : public Prototype
{
    public:
        ~ConcretePrototypeA() {}
        
        Prototype* clone(){
            return new ConcretePrototypeA();
        }
        std::string type(){
            return "type A";
        }
        // ...
};

class ConcretePrototypeB : public Prototype
{
    public:
        ~ConcretePrototypeB() {}
        
        Prototype* clone(){
            return new ConcretePrototypeB();
        }
        std::string type(){
            return "type B";
        }
        // ...
};

class Client
{
    private:
        static Prototype* types[2];
        static int n_types;
    public:
        static void init(){
            types[0]=new ConcretePrototypeA();
            types[1]=new ConcretePrototypeB();
        }

        static void remove(){
            delete types[0];
            delete types[1];
        }

        static Prototype* make(const int index){
            if(index>=n_types){
                return nullptr;
            }
            return types[index]->clone();
        }
        // ...
}; 

Prototype* Client::types[2];
int Client::n_types=2;

int main(){
    Client::init();

    Prototype* prototype1=Client::make(0);
    std::cout<<"Prototype: "<<prototype1->type()<<std::endl;
    delete prototype1;

    Prototype* prototype2=Client::make(1);
    std::cout<<"Prototype: "<<prototype2->type()<<std::endl;
    delete prototype2;

    Client::remove();

    return 0;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值