设计模式笔记——策略模式
来源:互联网 发布:windows企业版怎么下载 编辑:程序博客网 时间:2024/05/22 06:47
- 设计原则
- 策略模式
- 角色实现
- 行为算法族实现
- 测试类
设计原则
- 找出应用中可能会变化的部分,把它们独立出来,不要和那些不需要变化的代码混在一起。
- 针对接口编程,而不是针对实现编程。
- 多用组合,少用继承。
策略模式
定义了算法族(一组行为),分别封装起来,让他们之间可以相互替换。该模式让算法的变化独立于使用算法的用户。
应用示例:一个动作冒险游戏,有多个游戏角色和多种游戏武器,角色可以切换武器。
角色实现
// 抽象角色public abstract class Role { public abstract void fight(); //抽象行为,战斗}// 国王角色pubblic class King extends Role { public King() { name = "king"; } @Override public void fight() { if (weaponBehavior == null) { System.out.println(name + ": no weapon! With fist!"); } else { System.out.print(name + ": "); weaponBehavior.useWeapon(); } }}// 王后角色public class Queen extends Role { public Queen() { name = "queen"; } @Override public void fight() { if (weaponBehavior == null) { System.out.println(name + ": no weapon! With fist!"); } else { System.out.print(name + ": "); weaponBehavior.useWeapon(); } }}
行为(算法族)实现
// 抽象武器行为public interface WeaponBehavior { void useWeapon();}// 使用枪public class Gun implements WeaponBehavior { @Override public void useWeapon() { System.out.println("use gun to shoot."); }}// 使用匕首public class Knife implements WeaponBehavior { @Override public void useWeapon() { System.out.println("use knife to stab."); }}
测试类
//测试类public class Test { public static void main(String[] args) { // 国王角色 Role roleKing = new King(); roleKing.fight(); roleKing.setWeapon(new Knife()); roleKing.fight(); roleKing.setWeapon(new Gun()); roleKing.fight(); // 王后角色 Role roleQueen = new Queen(); roleQueen.fight(); roleQueen.setWeapon(new Gun()); roleQueen.fight(); roleQueen.setWeapon(new Knife()); roleQueen.fight(); }}
测试输出:
king: no weapon! With fist!king: use knife to stab.king: use gun to shoot.queen: no weapon! With fist!queen: use gun to shoot.queen: use knife to stab.
阅读全文
0 0
- 设计模式笔记——策略模式
- 设计模式笔记——策略模式
- 设计模式学习笔记—策略模式
- 设计模式笔记——策略设计模式
- 设计模式—策略模式
- 设计模式—策略模式
- 设计模式—策略模式
- 设计模式—策略模式
- 设计模式—策略模式
- 设计模式—策略模式
- 设计模式—策略模式
- 设计模式—策略模式
- 设计模式—策略模式
- 设计模式—策略模式
- 设计模式—策略模式
- 设计模式—策略模式
- 设计模式笔记(三)—— 策略模式
- 设计模式学习笔记——策略模式
- angular2_引入第三方文件之jQuery的引入
- 11.springboot整合默认spring cache
- CSS 终极之战:Grid VS Flexbox
- dns劫持!导致微信jssdk上挂广告
- 《文法俱乐部》读书笔记之辅语和基本句型--LG二进制
- 设计模式笔记——策略模式
- Android中的消息处理实例与分析
- 洛谷P2387 魔法森林_spfa
- Intellij IDEA使用(七)—— 使用Intellij IDEA配置Java(JavaWeb)项目jar包的两种方式
- SQL SERVER 中的行列转换小结
- c++ 中的特殊判断
- [Linux驱动炼成记]01-用户空间操作iic
- 在图片注入(伪静态注入)习题情况下得到的知识集合
- C++学习笔记--重载new和delete