原型模式:用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。
情景 :这个简单,就是需要拷贝东西的时候。
代码实例
#include <iostream>
#include <string>
using namespace std;
class Prototype
{
public :
Prototype(){}
virtual ~Prototype(){}
virtual Prototype * Clone() = 0;
virtual void Display()=0;
};
class ConcretePrototype : public Prototype
{
public :
ConcretePrototype():text("default"){}
virtual ~ConcretePrototype(){}
//拷贝构造函数
ConcretePrototype( const ConcretePrototype & ref)
{
text = ref .text;
}
virtual ConcretePrototype * Clone()
{
return new ConcretePrototype (*this );
}
void Display(){
cout<<text<<endl;
}
private :
string text;
};
int main(int argc , char **argv)
{
ConcretePrototype * conProA = new ConcretePrototype ();
ConcretePrototype * conProB = conProA->Clone();
conProA->Display();
conProB->Display();
delete conProA;
conProA= NULL ;
delete conProB;
conProB= NULL ;
return 0;
}
优点:
l 对客户隐藏了对象的创建工作
缺点:
l 每个子类都需重载不同的clone方法,略显复杂。