网站商城制作平台推广方式有哪些
前言
行为型模式是对在不同的对象之间划分责任和算法的抽象化。行为型模式不仅仅关注类和对象的结构,而且重点关注它们之间的相互作用。
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_H
main.h
#include <iostream>
#include "strategy.h"using 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));cout<<context->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;cin>>a>>b;Context *test=new Context('+');cout<<test>GetResult()<<endl;return 0;
}