本文章转载: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;
}