定义:
Prototype 模式, 用原型实例来指定出创建对象的总类,并且通过拷贝这些原型来创建新的对象。
使用场景
1.当一个系统应该独立于它的产品创建、构成和表示的时候; 2.当要实例化的类是在运行时刻指定的时候,如通过动态加载; 3.为了避免创建一个与产品类层次平行的工厂类层次时; 4.当一个类的实例只能有几个不同状态组合中的一种时。
代码实现
以电脑的生产来说,利用原型模式的概念,来分别生产不同品牌的电脑;该模式的主要特点是针对一个多个相似对象的情况,提供一个快速生成对象的方式。例如在本例中同一电脑,只有品牌是不同的,其他参数都是一样的。那我们就可以先用一个正常的对象,克隆出新的对象,然后再微调新对象的特殊属性。这样就达到快速生成相似对象的方法; 在C++,如果对象属性中含有指针,要注意指针的拷贝,需要先申请指针空间,然后再将指针内容复制过去。
代码如下:
/*
* 设计模式之原型模式
* */
#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();
return 0;
}
运行结果:
该款电脑相关参数如下: 品牌:华硕 CPU:I7 8700 内存:16g 显卡:gtx 1080 ti
该款电脑相关参数如下: 品牌:宏基 CPU:I7 8700 内存:16g 显卡:gtx 1080 ti