(二)策略模式
来源:互联网 发布:java工具书 编辑:程序博客网 时间:2024/05/01 09:03
#include <iostream>using namespace std;class operation{ public: operation( double a,double b ) { A = a; B = b; } virtual double get_result() { double result = 0; return result; } protected: double A,B;};class add : public operation{ public: add( double a, double b ):operation(a,b) {} double get_result() { return A+B; }};class sub : public operation{ public: sub( double a, double b ):operation(a,b) {} double get_result() { return A-B; }};class context{ public: context( operation *p ) : op(p) {} double result() { return op->get_result(); } private: operation *op;};int main(){ double a,b; char operate; context *t; cout << "输入运算式子" << endl; cin >> a >> operate >> b; switch( operate ) { case '+': t = new context( new add( a, b ) ); break; case '-': t = new context( new sub( a, b ) ); break; } cout << "结果是:" << t->result() << endl;}
如上,策略模式书上说的是定义算法家族,分别封装起来,让它们之间可以互相替换,让算法变化,不会影响到用户,例如上面的代码,在context中有一个operation对象(好像可以这么说=。=),当我们要实现加法的时候,context中会自己生成一个add,然后再由这个add算出结果,再返回结果,当然我们客户是不知道context中发生了什么的,我们只是知道我们传了一个式子进去并且得到我们想要的结果就行了。这样的话,当我们想要添加新功能的时候就不用修改context啦!
不过会发现我们把判断的工作交给客户端了,用书上的话来说就是要让业务逻辑和界面逻辑分开,降低他们之间的耦合度,才能达到容易为何和拓展,举个例子吧,如果有一家商场正在举办满300送100的活动,而你买了301的东西,那么你只需要还201了,可是,如果你不知道今天商场有这个活动,那收银员会不会坑你(即收你301)呢?正常来说不会吧,如果坑了你的话不就损失客源了?所以,判断的工作交给业务逻辑(收银员)会安全一点,要修改也只是修改业务逻辑就行了,业务逻辑可以看成是上面的context了。
综上,我们尝试将工厂模式应用到策略模式中,也就是在context类中增加一个判断的函数来决定生成什么类就行了:
#include <iostream>using namespace std;class operation{ public: operation() {} virtual double get_result() { double result = 0; return result; } void set_data( double a, double b ) { A = a; B = b; } protected: double A,B;};class add : public operation{ public: add():operation() {} double get_result() { return A+B; }};class sub : public operation{ public: sub():operation() {} double get_result() { return A-B; }};class context{ public: context( char operate ) { switch( operate ) { case '+': op = new add(); break; case '-': op = new sub(); break; } } double result() { return op->get_result(); } void set_operation( double a, double b ) { op->set_data( a, b ); } private: operation *op; };int main(){ double a,b; char operate; cout << "输入你的式子:" << endl; cin >> a >> operate >> b; context *p = new context( operate ); p->set_operation( a, b ); cout << "结果是:" << p->result() << endl; getchar(); getchar(); return 0;}
只是实现了基本的功能,细节可能处理的不是很好
0 0
- (二)策略模式
- (二)策略模式
- (二)策略模式
- 二、策略模式(策略工厂)
- 二、策略模式(Strategy)
- 初学设计模式二(策略模式)
- 设计模式心得(二) 策略模式
- 设计模式(二):策略模式
- 设计模式(二)策略模式
- 设计模式(二)--策略模式
- 设计模式(二)策略模式
- 设计模式(二十二) 策略模式
- 设计模式—策略模式(二)
- 设计模式(二):策略模式
- 策略(Strategy)模式 (二)
- 二 策略模式
- 二、策略模式
- 设计模式笔记(二)--策略模式、观察者模式
- python 动态类型
- Nyoj 246
- Cracking the coding interview--Q15.3
- 数据库的热备份和冷备份
- cocos2d-x 详解之 CCAction(动作)
- (二)策略模式
- C# 调用并执行SQL脚本文件
- mysql数据复制至redis的一种应用场景 bash实现
- SRM 613
- 利用HTML5 <canvas>实现2048小游戏
- QT TCP socket通信(二)
- Oracle建立表空间和用户
- 贪心法 区间选点问题 南阳oj 找点
- cf238