C++ 设计模式之原型模式

发布时间 2023-07-07 14:21:02作者: 一杯清酒邀明月

设计模式之原型模式

  原型模式是用原型实例指定创建兑现的种类,并且通过拷贝这些原型创建新的对象。原型模式说白了其实就是有一个把自己拷贝一下的方法。该模式很好理解,该模式独特地方不是类与类之间的关系,更多的是从语义上理解,只是实现了一个接口而已。

其UML图如下:

 

 示例代码如下:

 1 // PrototypeModel.h文件
 2 #pragma once
 3 #include <iostream>
 4 #include <string>
 5 // 原型类
 6 class Prototype
 7 {
 8 public:
 9     virtual Prototype * Clone() = 0;
10 };
11 // 
12 class ConcretePrototype_0 : public Prototype
13 {
14 public:
15     ConcretePrototype_0(std::string name)
16     {
17         m_strTypeName = name;
18     }
19     virtual Prototype * Clone()
20     {
21         ConcretePrototype_0 *p = new ConcretePrototype_0(m_strTypeName);
22         *p = *this;
23         return p;
24     }
25     void Show()
26     {
27         std::cout << m_strTypeName << std::endl;
28     }
29 private:
30     std::string m_strTypeName;
31 };
32 
33 class ConcretePrototype_1 : public Prototype
34 {
35 public:
36     ConcretePrototype_1(std::string name)
37     {
38         m_strTypeName = name;
39     }
40     virtual Prototype * Clone()
41     {
42         ConcretePrototype_1 *p = new ConcretePrototype_1(m_strTypeName);
43         *p = *this;
44         return p;
45     }
46     void Show()
47     {
48         std::cout << m_strTypeName << std::endl;
49     }
50 private:
51     std::string m_strTypeName;
52 };

测试代码如下:

 1 #include <iostream>
 2 #include "PrototypeModel.h"
 3 
 4 int main()
 5 {
 6     using namespace std;
 7     ConcretePrototype_0 * p1 = new ConcretePrototype_0("A");
 8     ConcretePrototype_1 * p2 = (ConcretePrototype_1 *)(p1->Clone());
 9     p1->Show();
10     p2->Show();
11     delete p1;
12     delete p2;
13 
14     getchar();
15     return 0;
16 }

测试结果如下图: