策略
定义一系列的算法,把它们一个个封装起来, 并且使它们可相互替换。本模式使得算法可独立于使用它的客户而变化.
实例
main.cc:
#include "player.h"
#include "slow_run.h"
#include "middle_run.h"
#include "fast_run.h"
#include <windows.h>
/*
design_pattern:"strategy"
Marathon training method:
speed slow ,distance long
speed middle , distance middle
speed fast,distance short
*/
int main(){
Player *player = new Player();
Run *slow_run = new SlowRun();
Run *middle_run = new MiddleRun();
Run *fast_run = new FastRun();
player->SetRun(slow_run);
player->Training();
player->SetRun(middle_run);
player->Training();
player->SetRun(fast_run);
player->Training();
//clear
delete player;
delete slow_run;
delete middle_run;
delete fast_run;
system("Pause");
return 0;
}
Player:
//player.h
#ifndef HELENDP_SOURCE_PLAYER_H_
#define HELENDP_SOURCE_PLAYER_H_
#include "run.h"
class Player{
public:
Player();
~Player();
void SetRun(Run *run);
void Training();
private:
Run *run_;
};
#endif
//player.cc
#include "player.h"
Player::Player(){
}
Player::~Player(){
}
void Player::SetRun(Run * run){
run_ = run;
}
void Player::Training(){
run_->Running();
}
Run:
//run.h
#ifndef HELENDP_SOURCE_RUN_H_
#define HELENDP_SOURCE_RUN_H_
class Run{
public:
Run();
virtual ~Run();
virtual void Running() = 0;
};
#endif
//run.cc
#include "run.h"
Run::Run(){
}
Run::~Run(){
}
void Run::Running(){
}
FastRun:
//fast_run.h
#ifndef HELENDP_SOURCE_FAST_RUN_H_
#define HELENDP_SOURCE_FAST_RUN_H_
#include "run.h"
class FastRun : public Run{
public:
FastRun();
~FastRun();
void Running();
};
#endif
//fast_run.cc
#include "fast_run.h"
#include <iostream>
using namespace std;
FastRun::FastRun(){
}
FastRun::~FastRun(){
}
void FastRun::Running(){
cout << "fast run method!" << endl;
}
MiddleRun:
//middle_run.h
#ifndef HELENDP_SOURCE_MIDDLE_RUN_H_
#define HELENDP_SOURCE_MIDDLE_RUN_H_
#include "run.h"
class MiddleRun : public Run{
public:
MiddleRun();
~MiddleRun();
void Running();
};
#endif
//middle_run.cc
#include "middle_run.h"
#include <iostream>
using namespace std;
MiddleRun::MiddleRun(){
}
MiddleRun::~MiddleRun(){
}
void MiddleRun::Running(){
cout << "middle run method!" << endl;
}
SlowRun:
//slow_run.h
#ifndef HELENDP_SOURCE_SLOW_RUN_H_
#define HELENDP_SOURCE_SLOW_RUN_H_
#include "run.h"
class SlowRun : public Run{
public:
SlowRun();
~SlowRun();
void Running();
};
#endif
//slow_run.cc
#include "slow_run.h"
#include <iostream>
using namespace std;
SlowRun::SlowRun(){
}
SlowRun::~SlowRun(){
}
void SlowRun::Running(){
cout << "slow run method!" << endl;
}
代码和UML图(EA)工程文件,最后会整理打包上传.
UML类图
结构
- Strategy(Run):策略类.
- ConcreteStrategy(FastRun,MiddleRun,SlowRun):具体策略类.
- Context(Player):上下文类.
优点
- 策略模式提供了对“开闭原则”的完美支持,用户可以在不修改原有系统的基础上选择算法或行为,也可以灵活地增加新的算法或行为.
- 策略模式提供了管理相关的算法族的办法.
- 策略模式提供了可以替换继承关系的办法.
- 使用策略模式可以避免使用多重条件转移语句.
缺点
- 客户端必须知道所有的策略类,并自行决定使用哪一个策略类.
- 策略模式将造成产生很多策略类,可以通过使用享元模式在一定程度上减少对象的数量.