策略模式:定义了算法族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化独立于使用算法的客户。
例子:设计一个鸭子类,有的鸭子会飞但有的不会飞;有的鸭子会叫但有的不会叫;所有的鸭子都有一个不同的外观。
1 public interface FlyBehavior 2 { 3 public void fly(); 4 } 5 6 public class FlyWithWings implements FlyBehavior 7 { 8 public void fly() 9 { 10 System.out.println("I'm flying!"); 11 } 12 } 13 14 public class FlyNoWay implements FlyBehavior 15 { 16 public void fly() 17 { 18 System.out.println("I can't fly!"); 19 } 20 } 21 22 public interface QuackBehavior 23 { 24 public void quack(); 25 } 26 27 public class Quack implements QuackBehavior 28 { 29 public void quack() 30 { 31 System.out.println("Quack!"); 32 } 33 } 34 35 public class MuteQuack implements QuackBehavior 36 { 37 public void quack() 38 { 39 System.out.println("<Silence>"); 40 } 41 } 42 43 public abstract class Duck 44 { 45 FlyBehavior flyBehavior; 46 QuackBehavior quackBehavior; 47 48 public abstract void display(); 49 50 public void performFly() 51 { 52 flyBehavior.fly(); 53 } 54 55 public void performQuack() 56 { 57 quackBehavior.quack(); 58 } 59 } 60 61 public class MallardDuck extends Duck 62 { 63 public MallardDuck(FlyBehavior flyBehavior, QuackBehavior quackBehavior) 64 { 65 this.quackBehavior = quackBehavior; 66 this.flyBehavior = flyBehavior; 67 } 68 69 @Override 70 public void display() 71 { 72 System.out.println("I'm a real Mallard Duck!"); 73 } 74 } 75 76 public class test 77 { 78 public static void main(String[] args) 79 { 80 Duck duck = new MallardDuck(new FlyWithWings(), new MuteQuack()); 81 duck.performFly(); 82 duck.performQuack(); 83 duck.display(); 84 } 85 }
参考:《headfirst设计模式》、http://yangguangfu.iteye.com/blog/815107