[英]Is this a correct implementation of the strategy pattern (JAVA, Fly method of ducks)?
我只想快速查看一下我正確實施了不同的飛行策略。
該程序僅由一個鴨子class 組成,該鴨子使用其飛行方法的接口。 該接口有不同的實現(即SimpleFly和NoFly ),switch 語句根據物種枚舉選擇正確的方法。
據我了解,策略模式旨在避免同一級別的子類之間的重復代碼,這會降低可維護性和可擴展性。 因此,我們將相關算法抽象為接口,並根據需要進行選擇。
代碼:
package DesignPatterns;
//Here we will separate the fly method of ducks into implementations of an internface and then instantiate ducks with those attributes
interface IFly {
public void fly();
}
//These are called strategies
class SimpleFly implements IFly {
@Override
public void fly() {
System.out.println("Quack Quack i am flying in the air");
}
}
class NoFly implements IFly {
@Override
public void fly() {
System.out.println("I cannot fly.");
}
}
//Now the base class just has to implement one of these strategies
class Duck {
private IFly flyType;
public enum SPECIE {
WILD, CITY, RUBBER
}
public Duck(SPECIE specie) {
switch(specie) {
//Here just select the algorithms you want to assign to each type of DUCK. More flexible than horizontal code between species.
case WILD:
case CITY:
this.flyType = new SimpleFly();
break;
case RUBBER:
this.flyType = new NoFly();
break;
default:
//If a new enum is defined but no definition yet, this stops code from breaking
this.flyType = new SimpleFly();
}
}
public void fly() {
flyType.fly();
}
}
output 是正確的,如下例所示:
Duck rubberDuck = new Duck(Duck.SPECIE.RUBBER);
Duck normalDuck = new Duck(Duck.SPECIE.WILD);
rubberDuck.fly();
normalDuck.fly();
產量:
I cannot fly.
Quack Quack i am flying in the air
提前謝謝你,請讓我知道我的知識差距,Sshawarma
我會指出幾個語義和術語問題。
fly
的方法可以實現為不飛行是令人困惑的。 將方法命名為tryToFly
或僅將方法記錄為嘗試是解決這種混淆的兩種方法。 這里要參考的軟件原理是 Liskov Substitution。Duck
應該直接在其構造函數(或 setter 方法)中接受IFly
的實例,而不是打開枚舉。 策略模式的另一個目標是避免分支邏輯。 該模式的本質是通過創建IFly
的多個實現來避免創建Duck
的多個子類。 這樣做的好處是可以在沒有復雜的 inheritance 層次結構的情況下重復使用這些IFly
實現,例如WILD
和CITY
可以共享一個策略。
正如評論中提到的,策略還具有Duck
可以在運行時更改其策略的優勢。 例如, IFly
可能由Soar
和Glide
實現,這樣Duck
可以根據風在這些不同的策略之間切換。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.