6 原型模式

 原型模式(Prototype):用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象。

原型模式其实就是从一个对象在创建一个可指定的对象,而且不需要知道任何创建的细节。

“一般在初始化的信息不发生变化的情况下,克隆是最好的方法。这既隐藏了对象创建的细节,又对性能是大大的提高。”

“...它等同于不用重新初始化对象,而是动态地获得对象运行时的状态。...”

实现Clone函数式,注意对引用或指针类型的复制,即浅复制和深复制的处理。

原型模式简单的C++实现版本
1 #include <iostream>
2 #include <string>
3
4  using std::string;
5
6  class Prototype
7 {
8  public:
9 Prototype(string id)
10 {
11 this->id = id;
12 }
13 void SetID(string newID)
14 {
15 this->id = newID;
16 }
17 virtual Prototype* Clone() = 0;
18  protected:
19 string id;
20 };
21
22  class ConcretePrototype1 : public Prototype
23 {
24  public:
25 ConcretePrototype1(string id) : Prototype(id)
26 {
27 }
28 Prototype* Clone()
29 {
30 ConcretePrototype1* p = new ConcretePrototype1(this->id);
31 *p = *this;
32 return p;
33 }
34 };
35
36  int main()
37 {
38 ConcretePrototype1* p1 = new ConcretePrototype1("1");
39 ConcretePrototype1* c1 = (ConcretePrototype1*)p1->Clone(); //通过克隆创建一个新的对象,带来性能的提升
40   c1->SetID("2"); //对新对象进行修改
41  
42 return 0;
43 }
原文地址:https://www.cnblogs.com/sifenkesi/p/1723365.html