原型模式

本文章转载:https://blog.csdn.net/u014337397/article/details/80387482

原型模式

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

使用场景:

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

代码实现

#include <iostream>
#include <string>
#include <list>
using 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();

    getchar();
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值