策略模式

行为模式:

 1 #include <iostream>
 2 
 3 class Base
 4 {
 5     public:
 6         virtual void show() = 0;
 7 };
 8 
 9 class Children1 : public Base
10 {
11     public:
12         void show()
13         {
14             std::cout<<"Children1"<<std::endl;
15         }
16 };
17 
18 class Children2 : public Base
19 {
20     public:
21         void show()
22         {
23             std::cout<<"Children2"<<std::endl;
24         }
25 };
26 
27 typedef enum _Enum
28 {
29     ONE = 1,
30     TWO = 2,
31 } MyEnum;
32 
33 #define CASE(num,classname) case num:obj=new classname();break;
34 class Context
35 {
36     public:
37         Context(MyEnum num)
38         :obj(nullptr)
39         {
40             switch(num)
41             {
42                 CASE(ONE,Children1)
43                 CASE(TWO,Children2)
44 
45                 default:
46                     break;
47             }
48         }
49 
50         void show()
51         {
52             obj->show();
53         }
54 
55         ~Context()
56         {
57             delete obj;
58         }
59     
60     public:
61         Base* obj;// = nullptr;
62 };
63 
64 int main()
65 {
66     Context context(ONE);
67     context.show();
68 }

代码非常类似简单工厂模式,只是多了一层封装,解决了 delete 的问题。 简单工厂模式是创建型模式,侧重对象的创建;策略模式是用来封装算法的。使用目的不一样 

posted @ 2013-04-12 17:41  轻典  阅读(146)  评论(0编辑  收藏  举报