1、算法接口類及實現算法
public interface FlyBehavior { public void fly(); } public interface QuackBehavior { public void quack(); }
public class FlyNoWay implements FlyBehavior{ public void fly() { System.out.println("I can't fly"); } } public class FlyWithWings implements FlyBehavior{ public void fly() { System.out.println("I'm flying"); } }
public class Quack implements QuackBehavior{ public void quack() { System.out.println("Quack"); } } public class Squeak implements QuackBehavior{ public void quack() { System.out.println("Squeak"); } } public class MuteQuack implements QuackBehavior { public void quack() { System.out.println("<< Silence >>"); } }
2、抽象類及具體實現類設計模式
public abstract class Duck { //爲行爲接口類型聲明兩個引用變量,全部的鴨子類都繼承它們 FlyBehavior flyBehavior; QuackBehavior quackBehavior; public Duck(){ } public abstract void display(); //委託給行爲類 public void performFly(){ flyBehavior.fly(); } public void performQuack(){ quackBehavior.quack(); } public void swim(){ System.out.println("All ducks float, even decoys!"); } //動態設定行爲 public void setFlyBehavior(FlyBehavior fb){ flyBehavior = fb; } public void setQuackBehavior(QuackBehavior qb){ quackBehavior = qb; } }
public class MallardDuck extends Duck { public MallardDuck(){ //根據需求選擇行爲 quackBehavior = new Quack(); flyBehavior = new FlyWithWings(); } public void display() { System.out.println("I'm a real Mallard duck"); } }
3、測試類測試
public class MinDuckSimulator { public static void main(String[] args){ Duck mallard = new MallardDuck(); mallard.performQuack(); mallard.performFly(); } }
4、類圖spa
LOL設計模式之「策略模式」code