原型模式(C++)

前言

  原型模式的思想,我们用的比较多(现在很多语言本身就带着这种思想,如Java),这种模式主要是考虑到一个对象在构造的时候可能参数比较多,如果以同样的方式去new的话,可读性不够强,另外,如果这个对象还携带一些数据,重新new的过程中可能会丢失部分数据,从而造成一些潜在的影响。在这种情况下,采用复制对象的方式比较可靠(根据需求选择是深拷贝还是浅拷贝,具体拷贝哪些数据)。

简单工厂模式

1. 概要

原型模式概要

2. 实现方法

/****** 原型模式 *****/
#ifndef PROTOTYPE_H
#define PROTOTYPE_H

#include <iostream>

using namespace std;

//提供一个克隆的基类
class Objdect
{
public:
    Objdect() {}
    virtual ~Objdect(){}

    virtual Objdect *clone() = 0;
    virtual void show() = 0;

    virtual void set_id(int id) = 0;
};

//开题实现克隆的类(以克隆羊为例)
class Object_sheeep : public Objdect
{
public:
    //可以看到这里的构造参数有5个(假设还有更多)
    Object_sheeep(int id,string name,int age,
                  string  father,string mother ) {
        this->m_id = id;
        this->m_name = name;
        this->m_age = age;
        this->m_father = father;
        this->m_mother = mother;
    }

    Objdect *clone() override{ //实现的关键部分
        return new Object_sheeep(*this);
    }

    void show() override{
        cout << "id:"<<this->m_id << endl;
        cout << "name:"<<this->m_name.data() << endl;
        cout << "age:"<<this->m_age << endl;
        cout << "father:"<<this->m_father.data() << endl;
        cout << "mother:"<<this->m_mother.data() << endl;
    }

    void set_id(int id) override{
        this->m_id = id;
    }
private:
    int m_id;
    string m_name;
    int m_age;
    string m_father;
    string m_mother;
};


//原型模式的应用实例
class Prototype
{
public:
    Prototype();
    void run_example(){
       cout << "***** Prototype *****" << endl;

       Objdect *sheep1 = new Object_sheeep(1,"sheep1",2,
                                           "sheep1_father","sheep2_mother");
       sheep1->show();

       cout << "clone a sheep...." << endl;

       //再构造一只羊的时候,由于参数太多(或者只是更改下部分参数)
       Objdect *sheep2 = sheep1->clone();
       sheep2->set_id(2);
       sheep2->show();

       delete sheep1;
       sheep1 = nullptr;
       delete sheep2;
       sheep2 = nullptr;
    }
};

#endif // PROTOTYPE_H

3. 设计模式总结

  总之,原型模式的理解比较简单,而且,现在很多的语言或框架均有着原型模式的思想了,在使用过程中,根据实际场景,组合使用原型模式。

  另外,C++中的一些设计模式的总结导航,可以参考这里(设计模式总结)。

参考资料

[1] https://www.runoob.com/design-pattern/prototype-pattern.html
[2] https://www.cnblogs.com/chengjundu/p/8473564.html

猜你喜欢

转载自www.cnblogs.com/treature/p/13198801.html