CH1 策略模式(Strategy Pattern)


Posted by newstart1117 on 2022-04-11

情境說明

有一款模擬鴨子的遊戲,遊戲中出現各種鴨子,一邊游泳戲水,一邊呱呱叫,並且也會飛


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.");
    }
}

程式碼連結

GitHub


#Design pattern #java #Strategy Pattern #sung







Related Posts

第一帖:認識 Git 時光機基礎

第一帖:認識 Git 時光機基礎

StyleGAN2 閱讀筆記

StyleGAN2 閱讀筆記

[Note] JS: Scope & Scope Chain

[Note] JS: Scope & Scope Chain


Comments