策略模式
来源:互联网 发布:网络公关公司找cyaa63 编辑:程序博客网 时间:2024/06/14 15:26
定义:将一系列相关算法封装成算法簇,使它们可以相互替换。使算法可以独立于使用者而变换。
适用场景:当类的行为经常发生变化时,可将其行为提取出来,将不同的行为封装成一个算法簇,对使用者只提供一个抽象接口。这样也满足了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 longusing 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的heroclass 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();}
0 0
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- [可持久化线段树] codeforces 707D. Persistent Bookcase
- Unity 中 transform.Find()的使用心得
- js创建对象的几种方式
- 编码、解码、分支结构
- C++ 11 新特性之容器相关特性
- 策略模式
- Java虚拟机学习 - JDK可视化监控工具
- LeetCode:377. Combination Sum IV
- Java虚拟机学习 - 对象引用强度
- C++基类与派生类的转换
- hihocoder 1356 分隔相同整数(贪心)
- Java反射机制
- Java虚拟机学习 - 内存调优
- Math.atan2() 方法