Prototype(DesignPattern)

Prototype

目的

用原型实例指定创建对象的种类,并且通过拷贝这些原型创建新的对象

动机

假设有一个框架,并希望增加一些表示符、休止符等对象来构造。我们可以为每个对象构造一个子类,但如果对象太多,子类太多不方便管理。因此为了解决这个问题,我们可以让框架通过拷贝或克隆一个graphic子类的实例来创建一个graphic。

使用范围

  • 希望动态加载类的实例时;
  • 为了避免创建一个与产品类层次平行的工厂类层次;
  • 当一个类的实力只能有几个不同状态组合中的一种时,可以通过建立一定的数量的原型,并通过克隆其建立对象;

效果

  • 动态添加和删除产品(客户能直接接触产品)
  • 随时改变结构,只需要通过修改参数值就可以生成新的对象;
  • 与factory method相比,子类的构造会更少;

由于是基于clone操作,因此内部存在不支持拷贝的对象会难以实现

代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <iostream>

class Prototype {
protected:
Prototype() { std::cout << "Prototype" << std::endl; }
public:
virtual Prototype* clone() const= 0;
virtual ~Prototype() { std::cout << "~Prototype" << std::endl; }
};

class ConcretePrototype1 : public Prototype{
public:
ConcretePrototype1(){ std::cout << "Prototype---A" << std::endl; }
virtual ~ConcretePrototype1() { std::cout << "~Prototype---A" << std::endl; }
ConcretePrototype1(const ConcretePrototype1&) { std::cout << "copy PrototypeA" << std::endl; }
virtual Prototype* clone() const{
return new ConcretePrototype1(*this);
}
};

class ConcretePrototype2 : public Prototype {
public:
ConcretePrototype2() { std::cout << "Prototype---B" << std::endl; }
virtual ~ConcretePrototype2() { std::cout << "~Prototype---B" << std::endl; }
ConcretePrototype2(const ConcretePrototype2&) { std::cout << "copy PrototypeB" << std::endl; }
virtual Prototype* clone() const {
return new ConcretePrototype2(*this);
}
};

class Manager {
public:
Prototype* _prototype1;
Prototype* _prototype2;
public:
Manager(){}
void register_protype(Prototype* p1, Prototype* p2) {
_prototype1 = p1->clone();
_prototype2 = p2->clone();
}
~Manager() {
/***It's safe to delete null pointer******/

/* _GLIBCXX_WEAK_DEFINITION void
* operator delete(void* ptr) throw ()
* {
* if (ptr)
* std::free(ptr);
* }
*/
delete _prototype1;
delete _prototype2;
}
};

int main()
{
Manager manager;
Prototype* p1 = new ConcretePrototype1();
Prototype* p2 = new ConcretePrototype2();
manager.register_protype(p1, p2);
delete p1;
delete p2;
return 0;
}