设计模式(六)

本文总阅读量

策略模式

简单的说就是(๑•ᴗ•๑):

  • 有好几个算法(方法)的接口一样,专门让一个类A去操作它,并且把实际的操作封装到A的方法中。

专业一点就是.(๑>؂<๑)۶:

  • 定义了算法家族,分别封装起来,让它们之间可以相互替换,从模式让算法的变化,不会影响到算法的客户。


介个问题且听下回分解(✿◡‿◡)

Strategy

做法

  • Context包含一个Strategy基类的指针,可以指向传入的Strategy子类对象
  • Context的getResult方法,直接用基类指针调用子类的方法实现功能
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/*
* Strategy.cpp
* 策略模式
* Created on: 2016年3月14日 下午4:30:31
* Author: Wayne 13186259527@163.com
*/


#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
using namespace std;

class CashSuper {
public:
virtual double acceptCash(double money) {
return 0;
}
};
//原价类
class CashNormal: public CashSuper {
public:
virtual double acceptCash(double money) {
return money;
}
};
//打折类
class CashRebate: public CashSuper {
private:
double moneyRebate;
public:
CashRebate(double mR) {
moneyRebate = mR;
}
virtual double acceptCash(double money) {
return money * moneyRebate;
}
};
//返现类
class CashReturn: public CashSuper {
private:
double moneyCondition;
double moneyReturn;
public:
CashReturn(double mC, double mR) {
moneyCondition = mC;
moneyReturn = mR;
}
virtual double acceptCash(double money) {
double reult = money;
if (money >= moneyCondition) {
reult = money - floor((money / moneyCondition)) * moneyReturn;
}
return reult;
}
};
//具体的操作类
class Context {
private:
CashSuper *cs;
public:
Context(CashSuper * CS) {
cs = CS;
}
double GetResult(double money) {
return cs->acceptCash(money);
}
};

int main(void) {
Context *c = NULL;
int choice;
double money;
double result;
//printf("hello\n");
cout << "请输入金额(>0):\n";
cin >> money;
cout << "请输入打折方式:" << endl;
cout << "1------原价" << endl;
cout << "2------打八折" << endl;
cout << "3------满300返100" << endl;
while (true) {
cin >> choice;
if (choice == 1 || choice == 2 || choice == 3) {
break;
}
cout << "输入有误,请输入1、2和3中任一数字" << endl;
}
switch (choice) {
case 1:
c = new Context(new CashNormal());
break;
case 2:
c = new Context(new CashRebate(0.8));
break;
case 3:
c = new Context(new CashReturn(300, 100));
break;
}
result = c->GetResult(money);
cout << "result = " << result << endl;
return 0;
}