さて、私は基本的に何をしたいのかという例で私の質問を始めたいと思います。静的メソッドを実行するために必要なデザインパターン
IDog
というインターフェースを実装して、実装にいくつかのメソッドを持たせたいと思っています。また、すべてのDog
クラスに基本属性とメソッドを与えるスーパークラスAbstractDog implements IDog
が必要です。次にサブクラスをPoodle extends AbstractDog
のようにしたいと思います。ここで私の問題はstatic
メソッドです - 基本的にAbstractDog
の各サブクラスに異なるstatic
メソッドを持たせたいですが、このメソッドをIDog
から実行できるようにしたいと考えています。
だから私のナイーブ(間違った)の実装は次のようになります。私が言ったように
public interface IDog {
String getName(); // every dog instance should be able to call name
static String getDescription(); // every dog class should be able to get its description
}
public abstract class AbstractDog implements IDog {
private String name; // every dog instance will have this
public AbstractDog(String name) {
this.name = name;
}
@Override
public String getName() {
return this.name; // every dog instance can call this
}
}
public class Poodle extends AbstractDog {
private static String description = "It's a poodle!"; // all Poodles have the same description
public Poodle(String name) {
super(name);
}
@Override // from IDog
public static String getDescription() {
return description;
}
}
さて、これは正しくないAbstractDog
クラスはgetDescription()
とIDog
は、そのメソッドの実装が必要static abstract
方法が必要になるため、それを上書きすることはできません。
私の問題にマッチするデザインパターンがあるかどうかを知りたいと思っています。(別の!)静的メソッドを実装するためにクラスのセットを強制します(中間のスーパークラスを持つことができます)。
一つの可能性は、私が発見したが、それは、有益な、あるいは十分でありenum DogType
の使用となり、その後、ちょうどDogType
属性でclass Dog
を持つかどうかはわからない:
public enum DogType {
Poodle("This is a poodle."), Havanese("This is a Havanese.)";
private String description;
private DogType(String description) {
this.description = description;
}
public String getDescription() {
return this.description;
}
}
public class Dog {
private String name;
private DogType dogType;
public Dog(String name, DogType dogType) {
this.name = name;
this.dogType = dogType;
}
public String getName() {
return this.name;
}
public String getDescription {
return this.dogType.getDescription();
}
}
しかし、この「回避策」は当初のアイデアよりも能力を失っています。インスタンスメソッドvoid prance()
のような唯一の犬のクラスには、今やPoodle
にアクセスできるような追加機能はありません。
同様の質問に関する多くのトピックはファクトリパターンを参照していますが、必ずしも構築方法が必要なわけではないため、私の問題にどのように適合するかはわかりません。そして、犬種族の数が増えるにつれて、私のコードが非常に混乱するようになると思います。あるいは、私の場合、Factoryをどのように正しく使うべきかを知りませんでした。
'public String getDescription(){ return"プードルです! "; } '??? – fabian