原型模式

介绍

原型模式(Prototype),用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

核心:是提供一个clone方法,通过该方法进行对象的拷贝 。

优点: 性能优良 ; 逃避构造函数的约束

缺点:每个类都要重写有clone方法,对于以后的类需要全面的考虑所有成员的拷贝

应用:一个复杂对象多个修改者的场景,该对象应该具有自我复制功能,统一一套接口。 资源优化场景 、 性能和安全要求的场景 

需要有抽象原型具体原型,抽象原型只需要有虚析构函数和纯虚方法clone即可,有具体原型实现clone方法

注意:clone内的操作要深拷贝,对于指针等成员变量不能只copy指针

UML类图

简单示例:

#ifndef SIMPLE_PROTOTYPE_H
#define SIMPLE_PROTOTYPE_H

#include <iostream>
using namespace std;

/**
 * @brief
 * 简单的原型模式
 */

class Prototype
{
public:
    virtual Prototype* Clone() = 0 ;
    virtual void show() = 0;

};

class ConcretePrototype1 : public Prototype
{
public:
    ConcretePrototype1()
    {
        m_name = "Prototype1";
        m_age = 0;
    }

    ConcretePrototype1(string name , int age)
    {
        m_name = name;
        m_age = age;
    }

    Prototype *Clone()
    {
        Prototype *temp = new ConcretePrototype1();

        if (nullptr != temp )
            return temp;
    }

    void show()
    {
        cout << "Name = "<<m_name<<"     Age = "<<m_age<<endl;
    }

private:
    string m_name;
    int m_age;
};


class ConcretePrototype2 : public Prototype
{
public:
    ConcretePrototype2()
    {
        m_name = "Prototype2";
        m_age = 1;
    }

    ConcretePrototype2(string name , int age)
    {
        m_name = name;
        m_age = age;
    }

    Prototype *Clone()
    {
        Prototype *temp = new ConcretePrototype2(m_name , m_age);

        if (nullptr != temp )
            return temp;
    }

    void show()
    {
        cout << "Name = "<<m_name<<"     Age = "<<m_age<<endl;
    }

private:
    string m_name;
    int m_age;
};

#endif // SIMPLE_PROTOTYPE_H

 调用:

    Prototype *t1 = new ConcretePrototype1;
    t1->show();


    Prototype *t2 = t1->Clone();
    t2->show();

    Prototype *t3 = new ConcretePrototype2("聂风" , 38);
    t3->show();

    Prototype *t4 = t3->Clone();
    t4->show();

欢迎各位大神在下方评论指导。随着以后对设计模式的认知加深,实时更新该文档。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Liu-Eleven

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值