策略模式定義了一系列的算法,並將每個算法封裝起來,並且使它們還能夠相互替換。策略模式讓算法獨立於使用它的客戶而獨立變化。
策略模式在應用時,是根據不一樣的使用狀況動態的選擇使用的算法,對於客戶來講,提供了很好的可擴展性和封閉性。
下面是代碼示例:
ios
#ifndef STRATEGY_H
#define STRATEGY_H
#include <iostream>
class Strategy//策略基類
{
public:
Strategy();
virtual ~Strategy(){std::cout << "~~\n";}
virtual void fun() = 0;
};
#endif // STRATEGY_H#include "strategy.h"Strategy::Strategy(){}#ifndef STRATEGYA_H#define STRATEGYA_H#include "strategy.h"class StrategyA : public Strategy{public:
StrategyA();~StrategyA(){}
void fun();};#endif // STRATEGYA_H#include "strategya.h"StrategyA::StrategyA(){}void StrategyA::fun(){std::cout << "策略A!走爲上" <<'\n';}#ifndef STRATEGYB_H#define STRATEGYB_H#include "strategy.h"class StrategyB : public Strategy{public:
StrategyB();~StrategyB(){}
void fun();};#endif // STRATEGYB_H#include "strategyb.h"StrategyB::StrategyB(){}void StrategyB::fun(){std::cout << "策略B!老婆天下第一,逛街去" <<'\n';}#ifndef STRATEGYC_H#define STRATEGYC_H#include "strategy.h"class StrategyC : public Strategy{public:
StrategyC();~StrategyC(){}
void fun();};#endif // STRATEGYC_H#include "strategyc.h"StrategyC::StrategyC(){}void StrategyC::fun(){std::cout << "策略C!金蟬脫殼" <<'\n';}#ifndef CONTEXT_H#define CONTEXT_H#include "strategy.h"class Context//應用的上下文類{public:
Context();Context(Strategy *p);~Context(){delete p_stratery;}void setStratery(Strategy *p) {delete p_stratery;p_stratery = p;}void useStratery() const {if(p_stratery != 0)p_stratery->fun();}private:
Strategy *p_stratery;};#endif // CONTEXT_H#include "context.h"Context::Context():p_stratery(0){}Context::Context(Strategy *p):p_stratery(p){}#include <iostream>using namespace std;#include "context.h"#include "strategya.h"#include "strategyb.h"#include "strategyc.h"int main(){cout << "老班讓加班!策略A..." << '\n';Context me(new StrategyA);me.useStratery();
cout << "老婆讓逛街!策略B..." << '\n';me.setStratery(new StrategyB);me.useStratery();
cout << "兄弟叫喝酒!可老婆讓早點回家!策略C..." << '\n';me.setStratery(new StrategyC);me.useStratery();
return 0;}最後來張運行圖