贵州省建设厅审图网站,vs 网站开发 mvc,一起做彩票网站的人,陕西找人做网站多少钱前言
行为型模式是对在不同的对象之间划分责任和算法的抽象化。行为型模式不仅仅关注类和对象的结构#xff0c;而且重点关注它们之间的相互作用。
Interpreter(解释器)
Template Method(模板方法)
GOOD#xff1a;把不变的代码部分都转移到父类中#xff0c;将可变的代…前言
行为型模式是对在不同的对象之间划分责任和算法的抽象化。行为型模式不仅仅关注类和对象的结构而且重点关注它们之间的相互作用。
Interpreter(解释器)
Template Method(模板方法)
GOOD把不变的代码部分都转移到父类中将可变的代码用 virtual 留到子类重写。
Chain of Responsibility(责任链)
Command(命令)
Iterator(迭代器)
Mediator(中介者)
Memento(备忘录)
Observer(观察者)
State(状态)
Strategy(策略)
定义算法家族分别封装起来让它们之间可以互相替换让算法变化不会影响到用户 GOOD适合类中的成员以方法为主算法经常变动简化了单元测试因为每个算法都有自己的类可以通过自己的接口单独测试。 策略模式和简单工厂基本相同但简单工厂模式只能解决对象创建问题对于经常变动的算法方法应使用策略模式。 BUG客户端要做出判断。
strategy.h
#ifndef CLION_TEST_STRATEGY_H
#define CLION_TEST_STRATEGY_H// 策略基类
class COperation {
public:int m_nFirst;int m_nSecond;virtual double GetResult() {double dResult 0;return dResult;}
};// 策略具体类——加法类
class AddOperation : public COperation {
public:AddOperation() {}AddOperation(int a, int b) {m_nFirst a;m_nSecond b;}double GetResult() final {return m_nFirst m_nSecond;}
};class Context {
private:COperation *op;
public:Context(COperation *temp) {op temp;}double GetResult() {return op-GetResult();}
};#endif //CLION_TEST_STRATEGY_Hmain.h
#include iostream
#include strategy.husing namespace std;int main() {system(chcp 65001);// 简单工厂模式int a 1;int b 2;// 策略模式char c ;switch (c) {case :Context* context new Context(new AddOperation(a,b));coutcontext-GetResult()endl;break;default:break;}return 0;
}策略模式与工厂结合
将实例化具体的类过程移至到Context对象的引用中。 strategy.h // 策略与工厂结合Context(char cType) {switch(cType) {case : op new AddOperation(3,8);break;default:op new AddOperation();break;}}main.h
int main()
{int a,b;cinab;Context *testnew Context();couttestGetResult()endl;return 0;
}Visitor(访问者)
后记