• 设计模式之Prototype(c++)


    Prototype模型:

    作用:

    用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象----克隆(clone)对象。


    Prototype模型类图如下:

    形象说明:如果客户想配钥匙(ConcretePrototype),就可以拿着钥匙去配钥匙的店铺,店铺老板会根据配的钥匙原型,给你配(Clone)钥匙!


    具体简单的实例实现:

    /*Prototype.hxx*/
    
    #ifndef _PROTOTYPE_H_
    #define _PROTOTYPE_H_
    
    class Prototype
    {
    public:
            virtual ~Prototype();
            virtual Prototype* Clone() const = 0;
    protected:
            Prototype();
    };
    
    class ConcretePrototype:public Prototype
    {
    public:
            ConcretePrototype();
            ConcretePrototype(const ConcretePrototype& cp);
            ~ConcretePrototype();
            Prototype* Clone() const;
    };
    #endif //~_PROTOTYPE_H_
    
    /*Prototype.cxx*/
    
    #include "Prototype.hxx"
    #include <iostream>
    
    using namespace std;
    
    Prototype::Prototype()
    {
    
    }
    
    Prototype::~Prototype()
    {
    
    }
    
    Prototype* Prototype::Clone() const 
    {
    	return 0;
    }
    
    //concretePrototype
    
    ConcretePrototype::ConcretePrototype()
    {
    
    }
    
    ConcretePrototype::~ConcretePrototype()
    {
    
    }
    
    ConcretePrototype::ConcretePrototype(const ConcretePrototype& cp)
    {
    	cout<< "ConcretePrototype copy..." << endl;
    }
    
    Prototype* ConcretePrototype::Clone() const
    {
    	return new ConcretePrototype(*this);
    }
    
    /*main.cxx*/
    
    #include "Prototype.hxx"
    
    #include <iostream>
    using namespace std;
    
    int main(int argc, char* argv[])
    {
    	Prototype* p = new ConcretePrototype();
    	Prototype* p1 = p->Clone();
    
    	cout << p <<"||" << p1 << endl;
    	
    	delete p;
    	p = NULL;
    	if (p1)
    	{
    		delete p1;
    		p1 = NULL;
    	}
    	return 0;
    }
    


    执行结果:

    liujl@liujl-ThinkPad-Edge-E431:~/mysource/Design_model/Prototype$ g++ -o main main.o Prototype.o
    liujl@liujl-ThinkPad-Edge-E431:~/mysource/Design_model/Prototype$ ./main 
    ConcretePrototype copy...
    0xf11010||0xf11030


    参考文档:

    1、c++设计模式.pdf

    2、常见设计模式的解析和实现(C++)之四-Prototype模式

  • 相关阅读:
    蓝牙音箱的连接和断开
    画一个钟表,陪着我走
    利用MediaSession发送信息到蓝牙音箱
    修改Switch 的颜色
    ViewPager PagerAdapter 的使用
    错误:android.view.InflateException: Binary XML file line #167: Binary XML file line #167: Error inflating class <unknown>
    react-project(一)
    create-react-app重建
    nodeJS连接mysql
    nodeJS问题
  • 原文地址:https://www.cnblogs.com/riasky/p/3459038.html
Copyright © 2020-2023  润新知