代码实现
1 class Strategy
2 {
3 public:
4 Strategy() {}
5
6 virtual void AlgrithmInterface() = 0; //算法族接口
7
8 virtual ~Strategy()
9 {
10 cout << "Strategy Destruction called." << endl;
11 }
12 };
13
14 class ConcrateStrategyA : public Strategy
15 {
16 public:
17 ConcrateStrategyA() {}
18
19 virtual void AlgrithmInterface()
20 {
21 cout << "ConcrateStrategyA AlgrithmInterface Called." << endl;
22 }
23
24 virtual ~ConcrateStrategyA()
25 {
26 cout << "ConcrateStrategyA Destruction called" << endl;
27 }
28 };
29
30 class ConcrateStrategyB : public Strategy
31 {
32 public:
33 ConcrateStrategyB() {}
34
35 virtual void AlgrithmInterface()
36 {
37 cout << "ConcrateStrategyB AlgrithmInterface Called." << endl;
38 }
39
40 virtual ~ConcrateStrategyB()
41 {
42 cout << "ConcrateStrategyB Destruction Called" << endl;
43 }
44 };
45
46
47 class Context
48 {
49 public:
50 Context(Strategy *pStrategy)
51 {
52 mStrategy = pStrategy;
53 }
54
55 void DoAction()
56 {
57 if (mStrategy)
58 {
59 mStrategy->AlgrithmInterface();
60 }
61 }
62
63 void SetStrategy(Strategy *pStrategy)
64 {
65 mStrategy = pStrategy;
66 }
67 ~Context()
68 {
69 if (mStrategy)
70 {
71 delete mStrategy;
72 mStrategy = NULL;
73 }
74 }
75 private:
76 Strategy *mStrategy;
77 };
78
79 int _tmain(int argc, _TCHAR* argv[])
80 {
81 ConcrateStrategyA *strategyA = new ConcrateStrategyA;
82 ConcrateStrategyB *strategyB = new ConcrateStrategyB;
83 Context context(strategyA);
84 context.DoAction();
85
86 context.SetStrategy(strategyB);
87 context.DoAction();
88
89 delete strategyA;
90 strategyA = NULL;
91 delete strategyB;
92 strategyB = NULL;
93 getchar();
94 return 0;
95 }
Head First 设计模式中鸭子实例