策略模式
为了满足不同子类具有不同的行为而设计
而且,它可以提供行为/算法的互换,使行为具有可变性
而且,支持扩展新的行为而不影响原有的代码
Sample1:
package pattern.strategy; /** * 策略模式 * 实现一组可相互切换的行为类/算法簇 */ public class StrategyExample { public static void main(String[] args) { int a = 1, b = 2; Strategy originalStrategy = new Add(); Context c = new Context(originalStrategy); int result = c.executeStrategy(a, b); System.out.println(result); //当某种条件发生时,切换策略 Strategy newStrategy = new Subtract(); c.changeStrategy(newStrategy); result = c.executeStrategy(a, b); System.out.println(result); } } class Context { private Strategy strategy; public Context(Strategy strategy) { this.strategy = strategy; } //对外提供改变策略的方法 public void changeStrategy(Strategy strategy) { this.strategy = strategy; } public int executeStrategy(int a, int b) { return this.strategy.execute(a, b); } } /** * 找出可能会发生变化的地方,独立进行封装 * 策略经常发生变化,所以要将其独立出来,与那些不变的代码进行隔离 */ interface Strategy { int execute(int a, int b); } class Add implements Strategy { public int execute(int a, int b) { return a + b; } } class Subtract implements Strategy { public int execute(int a, int b) { return a - b; } } class Multiply implements Strategy { public int execute(int a, int b) { return a * b; } }
Sample 2:
package pattern.strategy; public class FightDemo { public static void main(String[] args) { Character c = new Knight(); c.setWeapon(new AxeBehavior()); c.fight(); //更换武器 c.setWeapon(new SwordBehavior()); c.fight(); } } //========================================= abstract class Character { protected WeaponBehavior weapon; void setWeapon(WeaponBehavior w) { this.weapon = w; } abstract void fight(); } class Knight extends Character { @Override void fight() { System.out.println(Knight.class.getName() +" is fighting..."); this.weapon.useWeapon(); } } class King extends Character { @Override void fight() { System.out.println(King.class.getName() +" is fighting..."); this.weapon.useWeapon(); } } //========================================= /** * 行为接口 */ interface WeaponBehavior { void useWeapon(); } //行为一 class SwordBehavior implements WeaponBehavior { public void useWeapon() { System.out.println("Use sword!"); } } //行为二 class AxeBehavior implements WeaponBehavior { public void useWeapon() { System.out.println("Use axe!"); } }
扫描二维码关注公众号,回复:
1166614 查看本文章