来自于《大话设计模式》
策略模式(Strategy):它定义了算法家族,分别封装起来,让它们之间可以相互替换,此模式让算法的变化不会影响到使用算法的客户。
所谓的算法即使 acceptCash 虚函数,由 CashSuper 的派生类实现各个 acceptCash。客户端代码根据使用不同的参数生成不同的 CashContext 对象,来使用不同的策略(acceptCash 虚函数)
UML 图:
代码实现 C++:
1 #include <iostream>
2 using namespace std;
3
4 class CashSuper
5 {
6 public:
7 virtual double acceptCash(double money) = 0;
8 };
9
10 class CashNormal : public CashSuper
11 {
12 public:
13 virtual double acceptCash(double money)
14 {
15 return money;
16 }
17 };
18
19 class CashRebate : public CashSuper
20 {
21 private:
22 double moneyRebate;
23 public:
24 CashRebate(double mr = 1.0) : moneyRebate(mr) {}
25 virtual double acceptCash(double money)
26 {
27 return money * moneyRebate;
28 }
29 };
30
31 class CashReturn : public CashSuper
32 {
33 private:
34 double moneyCondition;
35 double moneyReturn;
36 public:
37 CashReturn(double c = 1.0, double r = 1.0) : moneyCondition(c), moneyReturn(r) {}
38 virtual double acceptCash(double money)
39 {
40 return money - money / moneyCondition * moneyReturn;
41 }
42 };
43
44 class CashContext
45 {
46 private:
47 CashSuper* cs;
48 public:
49 CashContext()
50 {
51 cs = new CashNormal;
52 // cs = new CashNormal();
53 }
54 CashContext(double r)
55 {
56 cs = new CashRebate(r);
57 }
58 CashContext(double c, double r)
59 {
60 cs = new CashReturn(c, r);
61 }
62 ~CashContext()
63 {
64 delete cs;
65 }
66 double GetResult(double money)
67 {
68 return cs->acceptCash(money);
69 }
70 };
71
72 int main()
73 {
74 CashContext* cc = new CashContext;
75 cout << cc->GetResult(300) << endl;
76 delete cc;
77
78 cc = new CashContext(0.8);
79 cout << cc->GetResult(300) << endl;
80 delete cc;
81
82 cc = new CashContext(100, 50);
83 cout << cc->GetResult(300) << endl;
84 delete cc;
85
86 return 0;
87 }
posted on 2011-04-23 16:27
unixfy 阅读(157)
评论(0) 编辑 收藏 引用