C++ 原型模式

2021/6/2 12:20:54

本文主要是介绍C++ 原型模式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

定义:

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

使用场景

1.当一个系统应该独立于它的产品创建、构成和表示的时候; 2.当要实例化的类是在运行时刻指定的时候,如通过动态加载; 3.为了避免创建一个与产品类层次平行的工厂类层次时; 4.当一个类的实例只能有几个不同状态组合中的一种时。

代码实现

以电脑的生产来说,利用原型模式的概念,来分别生产不同品牌的电脑;该模式的主要特点是针对一个多个相似对象的情况,提供一个快速生成对象的方式。例如在本例中同一电脑,只有品牌是不同的,其他参数都是一样的。那我们就可以先用一个正常的对象,克隆出新的对象,然后再微调新对象的特殊属性。这样就达到快速生成相似对象的方法;  在C++,如果对象属性中含有指针,要注意指针的拷贝,需要先申请指针空间,然后再将指针内容复制过去。

代码如下:

/*
 * 设计模式之原型模式
 * */

#include#include#includeusing namespace std;

//产品类
class Computer
{
public:
    void SetBrandName(string brandName)         //设置品牌
    {
        this->m_BrandName = brandName;
    }

    void SetCpu(string cpu)                     //设置CPU
    {
        this->m_Cpu = cpu;
    }

    void SetMemory(string memory)               //设置内存
    {
        this->m_Memory = memory;
    }

    void SetVideoCard(string videoCard)        //设置显卡
    {
        this->m_VideoCard=videoCard;
    }

    Computer Clone()                               //克隆函数
    {
        Computer ret;
        ret.SetBrandName(this->m_BrandName);
        ret.SetCpu(this->m_Cpu);
        ret.SetMemory(this->m_Memory);
        ret.SetVideoCard(this->m_VideoCard);
        return ret;
    }

    void ShowParams()                         //显示电脑相关信息
    {
        cout << "该款电脑相关参数如下:" << endl;
        cout << "品牌:" << this->m_BrandName << endl;
        cout << "CPU:" << this->m_Cpu << endl;
        cout << "内存:" << this->m_Memory << endl;
        cout << "显卡:" << this->m_VideoCard << endl;
    }

private:
    string m_BrandName;                         //品牌
    string m_Cpu;                               //CPU
    string m_Memory;                            //内存
    string m_VideoCard;                         //显卡
};

//本例以电脑代工厂为例,分别生产同一配置,不同品牌的电脑
int main()
{
    //先生产华硕电脑
    Computer asusComputer;
    asusComputer.SetBrandName("华硕");
    asusComputer.SetCpu("I7 8700");
    asusComputer.SetMemory("16g");
    asusComputer.SetVideoCard("gtx 1080 ti");
    asusComputer.ShowParams();

    cout << endl;

    //再生产宏基电脑
    Computer acerComputer = asusComputer.Clone();
    acerComputer.SetBrandName("宏基");
    acerComputer.ShowParams();

    return 0;
}

运行结果:

该款电脑相关参数如下: 品牌:华硕 CPU:I7 8700 内存:16g 显卡:gtx 1080 ti

该款电脑相关参数如下: 品牌:宏基 CPU:I7 8700 内存:16g 显卡:gtx 1080 ti



这篇关于C++ 原型模式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程