码迷,mamicode.com
首页 > 编程语言 > 详细

Prototype 模式示例代码 (C++)

时间:2015-08-28 21:12:19      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

 1 // --------------------------------------------------------------------------------------
 2 /** Abstract.h **/
 3 
 4 class Abstract {
 5 private:
 6     typedef map<type_t, Abstract*> RegMap;
 7     static RegMap& getRegistry() { 
 8         static RegMap registry; // initialized at the first time the function is called  
 9         return registry;
10     }
11 public:
12     Abstract(const type_t& type) {
13         if (lookup(type) != NULL)
14             getRegistry.insert(type, this);
15     }
16 
17     virtual ~Abstract() { }
18 
19     virtual Abstract* clone() = 0;  
20 
21     static Abstract* create(const type_t& type) { 
22         Abstract* stub = lookup(type);
23         return stub != NULL : stub->clone() : NULL; 
24     }
25 
26     virtual void destroy() { delete this; }
27 
28     static const Abstract* lookup(const type_t& type) {
29         if (getRegistry().find(type) != getRegistry().end())
30             return getRegistry()[type];
31         return NULL;
32     }
33 };
34 
35 // --------------------------------------------------------------------------------------
36 /** ConcreteA.h **/
37 
38 class ConcreteA : public Abstract {
39     // ... data members
40     ConcreteA* clone() { return new ConcreteA(*this); }
41 public:
42     ConcreteA() : Abstract(CONC_TYPE_A) { } // CONC_TYPE_A : constant
43     // ... other members
44 };
45 
46 // --------------------------------------------------------------------------------------
47 /** ConcreteA.cpp **/
48 
49     static ConcreteA __concrete_a_stub/*(...)*/; // static initialized
50 
51 // --------------------------------------------------------------------------------------
52 /** ConcreteB.h **/
53 
54 class ConcreteB : public Abstract {
55     // ... data members
56     ConcreteB* clone() { return new ConcreteB(*this); }
57 public:
58     ConcreteB() : Abstract(CONC_TYPE_B) { } // CONC_TYPE_B : constant
59     // ... other members
60 };
61 
62 // --------------------------------------------------------------------------------------
63 /** ConcreteB.cpp **/
64 
65     static ConcreteB __concrete_b_stub/*(...)*/; 
66 
67 // --------------------------------------------------------------------------------------
68 /** Client **/
69 
70 Abstract* p_abstract = Abstract::create(CONC_TYPE_A /* or CONC_TYPE_B */);
71 // ... some code
72 p_abstract->destroy();
73 
74 // --------------------------------------------------------------------------------------

 

Prototype 模式示例代码 (C++)

标签:

原文地址:http://www.cnblogs.com/bestofme/p/4767657.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!