2 策略模式(1)

策略

 

 

代码
1 #include <iostream>
2 #include <string>
3
4  using std::cout;
5  using std::endl;
6
7  class Strategy
8 {
9 public:
10 virtual void AlgorithmInterface() = 0;
11 };
12
13 //具体算法A
14 class ConcreteStrategyA : public Strategy
15 {
16 public:
17 void AlgorithmInterface()
18 {
19 cout<<"算法A实现"<<endl;
20 }
21 };
22
23 //具体算法B
24 class ConcreteStrategyB : public Strategy
25 {
26 public:
27 void AlgorithmInterface()
28 {
29 cout<<"算法B实现"<<endl;
30 }
31 };
32
33 //具体算法A
34 class ConcreteStrategyC : public Strategy
35 {
36 public:
37 void AlgorithmInterface()
38 {
39 cout<<"算法C实现"<<endl;
40 }
41 };
42
43 //Context,用一个ConcreteStrategy来配置,维护一个对Strategy对象的引用
44 class Context
45 {
46 public:
47 Context(Strategy* strategy) //初始化时,传入具体的策略对象
48 {
49 this->strategy = strategy;
50 }
51 void ContextInterface() //根据具体的策略对象,调用其算法的方法
52 {
53 strategy->AlgorithmInterface();
54 }
55 private:
56 Strategy* strategy;
57 };
58
59 int main()
60 {
61 //客户端代码
62 Context* context = NULL;
63
64 context = new Context(new ConcreteStrategyA());
65 context->ContextInterface();
66
67 context = new Context(new ConcreteStrategyB());
68 context->ContextInterface();
69
70 context = new Context(new ConcreteStrategyC());
71 context->ContextInterface();
72
73 return 0;
74 }

 

 

 

posted @ 2010-04-24 23:35  斯芬克斯  阅读(280)  评论(0编辑  收藏  举报