标签:
两种表现行为,即要实现两个算法族,封装为两个接口,分别是QuackBehavior和FlyBehavior接口:
1 package com.nwpulisz.strategypattren; 2 public interface QuackBehavior { 3 public void quack(); 4 }
1 package com.nwpulisz.strategypattren; 2 public interface FlyBehavior { 3 public void fly(); 4 }
1 package com.nwpulisz.strategypattren; 2 public class Quack implements QuackBehavior { 3 public void quack() { 4 // TODO Auto-generated method stub 5 System.out.println("Quack"); 6 } 7 }
1 package com.nwpulisz.strategypattren; 2 public class MuteQuack implements QuackBehavior { 3 public void quack() { 4 // TODO Auto-generated method stub 5 System.out.println("Mute Quck"); 6 } 7 }
1 package com.nwpulisz.strategypattren; 2 public class FlyNoWay implements FlyBehavior { 3 public void fly() { 4 // TODO Auto-generated method stub 5 System.out.println("fly no way"); 6 } 7 }
1 package com.nwpulisz.strategypattren; 2 public class FlyWithWings implements FlyBehavior { 3 public void fly() { 4 // TODO Auto-generated method stub 5 System.out.println("fly with wings"); 6 } 7 }
1 package com.nwpulisz.strategypattren; 2 public abstract class Duck { 3 FlyBehavior flyBehavior; //为行为接口类型声明两个引用变量,所有鸭子的子类都会继承它们; 4 QuackBehavior quackBehavior; 5 public Duck(){ 6 7 } 8 public abstract void display(); 9 10 public void performFly(){ 11 flyBehavior.fly(); //行为的执行委托给行为类; 12 } 13 public void performQuack(){ 14 quackBehavior.quack(); 15 } 16 17 public void setFlyBehavior(FlyBehavior flyBehavior) { 18 this.flyBehavior = flyBehavior; 19 } 20 public void setQuackBehavior(QuackBehavior quackBehavior) { 21 this.quackBehavior = quackBehavior; 22 } 23 24 }
1 package com.nwpulisz.strategypattren; 2 public class MallardDuck extends Duck { 3 public MallardDuck(){ 4 quackBehavior=new Quack(); //构造器中指定行为类; 5 flyBehavior= new FlyWithWings(); 6 } 7 @Override 8 public void display() { 9 // TODO Auto-generated method stub 10 System.out.println("Mallar Duck"); 11 } 12 }
1 package com.nwpulisz.strategypattren; 2 public class DuckSimulator { 3 4 public static void main(String[] args) { 5 // TODO Auto-generated method stub 6 Duck mallard = new MallardDuck(); 7 mallard.performQuack(); //构造器中指定行为类,output:Quack; 8 mallard.performFly(); //构造器中指定行为类,output:fly with wings; 9 10 mallard.setFlyBehavior(new FlyNoWay()); //调用set方法,可以动态改变行为; 11 mallard.setQuackBehavior(new MuteQuack()); //调用set方法,可以动态改变行为; 12 mallard.performQuack(); //output:Mute Quck; 13 mallard.performFly(); //output:fly no way; 14 } 15 }
标签:
原文地址:http://www.cnblogs.com/nwpulisz/p/5380084.html