情境說明
有一款模擬鴨子的遊戲,遊戲中出現各種鴨子,一邊游泳戲水,一邊呱呱叫,並且也會飛
Duck類別
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 interface FlyBehavior {
public void fly();
}
public interface QuackBehavior {
public void quack();
}
實作叫聲與飛行方式
public class FlyWithWings implements FlyBehavior {
@Override
public void fly() {
System.out.println("I'm flying!!");
}
}
public class Quack implements QuackBehavior {
@Override
public void quack() {
System.out.println("Quack");
}
}
各類型鴨子
//綠頭鴨
public class MallardDuck extends Duck{
public MallardDuck() {
quackBehavior = new Quack();
flyBehavior = new FlyWithWings();
}
@Override
public void display() {
System.out.println("I'm a real Mallard duck");
}
}
//模型鴨
public class ModelDuck extends Duck{
public ModelDuck() {
flyBehavior = new FlyNoWay();
quackBehavior = new Quack();
}
@Override
public void display() {
System.out.println("I'm a model duck.");
}
}