策略模式
2016-08-21 16:04
302 查看
定义:将一系列相关算法封装成算法簇,使它们可以相互替换。使算法可以独立于使用者而变换。
适用场景:当类的行为经常发生变化时,可将其行为提取出来,将不同的行为封装成一个算法簇,对使用者只提供一个抽象接口。这样也满足了OO三大原则:封装变化,针对接口编程,多用组合少用继承.
组成:
strategy: 定义所有支持的算法的公共接口
concrete strategy: 实现了具体的算法行为,继承于strategy。
Context :用一个ConcreteStrategy来配置,维护一个对Strategy对象的引用
UML图:
代码:
适用场景:当类的行为经常发生变化时,可将其行为提取出来,将不同的行为封装成一个算法簇,对使用者只提供一个抽象接口。这样也满足了OO三大原则:封装变化,针对接口编程,多用组合少用继承.
组成:
strategy: 定义所有支持的算法的公共接口
concrete strategy: 实现了具体的算法行为,继承于strategy。
Context :用一个ConcreteStrategy来配置,维护一个对Strategy对象的引用
UML图:
代码:
#include <cstdio> #include <stack> #include <set> #include <iostream> #include <string> #include <vector> #include <queue> #include <list> #include <functional> #include <cstring> #include <algorithm> #include <cctype> #include <string> #include <map> #include <iomanip> #include <cmath> #include <time.h> #define LL long long using namespace std; // 定义一个武器的接口,英雄可以使用不同的武器,并且可以替换武器 class weapon { public: virtual void use_weapon()=0; }; class sword:public weapon { public: void use_weapon() { puts("use a sword"); } }; class axe:public weapon { public: void use_weapon() { puts("use a axe"); } }; // 定义使用weapon的hero class hero { private: weapon *weap; public: hero(weapon *p):weap(p) {} void change_weap(weapon *p) { delete weap; weap = p; } void attack() { weap->use_weapon(); } }; int main() { hero combatant(new sword); combatant.attack(); combatant.change_weap(new axe); combatant.attack(); }
相关文章推荐
- 设计模式之Strategy(策略)
- 设计模式(20)-策略模式(Strategy)
- 策略模式之C++版本
- 应用泛型的策略模式
- 对象模型--策略、模式、应用 笔记1
- [浪子学编程][MS Enterprise Library]ObjectBuilder之设计模式(一):策略模式
- (22)策略模式-Strategy Pattern-康熙收复台湾-明珠和索额图的不同策略
- 从诸葛亮的三个锦囊妙计谈策略模式
- 《Java与模式》学习笔记之九-----策略模式(Strategy Pattern)
- AspectJ实现设计模式(二)——策略模式
- 设计模式之Strategy(策略)
- 设计模式之Strategy(策略)
- 策略模式之C#版本(原创翻译版本)
- 设计模式实战(一)——使用策略模式(strategy pattern)实现多关键字排序
- Delphi模式编程之策略模式(下)
- 設計模式之Strategy(策略)
- 深入浅出策略模式
- 设计模式——策略模式
- 设计模式之策略模式(Strategy)
- 对象模型--策略、模式、应用 笔记2---选择对象