2 策略模式(1)

策略

 

 

ContractedBlock.gif ExpandedBlockStart.gif 代码
 
   
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 }

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值