设计模式笔记——策略模式
2017-12-13 23:17
337 查看
设计原则
策略模式
角色实现
行为算法族实现
测试类
针对接口编程,而不是针对实现编程。
多用组合,少用继承。
应用示例:一个动作冒险游戏,有多个游戏角色和多种游戏武器,角色可以切换武器。
测试输出:
策略模式
角色实现
行为算法族实现
测试类
设计原则
找出应用中可能会变化的部分,把它们独立出来,不要和那些不需要变化的代码混在一起。针对接口编程,而不是针对实现编程。
多用组合,少用继承。
策略模式
定义了算法族(一组行为),分别封装起来,让他们之间可以相互替换。该模式让算法的变化独立于使用算法的用户。应用示例:一个动作冒险游戏,有多个游戏角色和多种游戏武器,角色可以切换武器。
角色实现
// 抽象角色 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 = ne 97c1 w 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.
相关文章推荐
- Android 设计模式 笔记 - 策略模式
- 个人笔记整理-java设计模式之策略模式
- 【学习笔记】设计模式-策略模式
- 设计模式学习笔记-策略模式
- 设计模式 学习笔记 之 策略模式 Strategy(4)
- Java设计模式笔记之策略模式
- 学习笔记 ---- 设计模式之策略模式
- 深入浅出设计模式笔记之十七:策略模式
- 设计模式之策略模式--慕课网笔记
- 设计模式学习笔记--Strategy 策略模式
- 设计模式之策略模式笔记
- 二 策略模式——设计模式学习笔记
- 设计模式学习笔记二【策略模式】
- java/android 设计模式学习笔记(17)---策略模式
- 再起航,我的学习笔记之JavaScript设计模式20(策略模式)
- 设计模式学习笔记之(二、策略模式)
- HeadFirst 设计模式学习笔记1--策略模式
- 设计模式笔记之---策略模式
- 设计模式笔记-策略模式
- 设计模式学习笔记七:策略模式