3

私が持っているとします:

public class FightingZone<MobileSuitso, Background> {

    private MobileSuitCollection<MobileSuitso> msCollection;
    private BackgroundInfo<Background> bgInfo;

    public FightingZone(MobileSuitCollection<MobileSuitso> newCollection, BackgroundInfo<Background> newInfo) {
        this.msCollection = newCollection;
        this.bgInfo = newInfo;
    }

    ...

        ...// inside a method
        MobileSuitCollection temporaryCollection = new MobileSuitCollection<MobileSuitso>(); // /!\

}

問題は、MobileSuitCollection がインターフェイスであるため、インスタンス化できないことです。たとえば、次のことができます。

MobileSuitCollection temporaryCollection = new GundamMeisterCollection<MobileSuitso>();
MobileSuitCollection temporaryCollection = new InnovatorCollection<MobileSuitso>();
MobileSuitCollection temporaryCollection = new CannonFolderCollection<MobileSuitso>();

など。ただし、を操作するtemporaryCollectionには、パラメーターを介してクラスに渡されたものと同じタイプである必要があります。だから私はこれを行うことを考えました:

if (msCollection instanceof GundamMeisterCollection) {
    ...
} else if (msCollection instanceof InnovatorCollection) {
    ...
} ...

しかし、それはひどいことだと思います。これを行うより良い方法はありますか?初期型で使用されるクラスへの参照を保持し、それをインスタンス化することは可能temporaryCollectionでしょうか?

4

2 に答える 2

2

if 句に配置するコードは、次のように配置できますVisitor

// Generics skipped for brevity
interface MobileSuitCollectionVisitor {
   handleCollection(GundamMeisterCollection collection);
   handleCollection(InnovatorCollection collection);
   handleCollection(CannonFolderCollection collection)
}

class ConcreteVisitor implements MobileSuitCollectionVisitor { 
    // place all of the logic in the implemented methods
}

そしてMobileSuitCollection、メソッドを持ってみましょう:

void visit(MobileSuitCollectionVisitor visitor);

そして、MobileSuitCollection単に持っているの各実装で

public void visit(MobileSuitCollectionVisitor visitor) {
    visitor.handleCollection(this);
}
于 2010-06-29T21:15:18.797 に答える
0

それを行う簡単で汚い方法は、元のコレクションのクローンを作成し、必要に応じて操作することです。より良い方法はnewInstance()、インターフェイスにメソッドを追加するか、ファクトリを に渡すことFightingZoneです。

于 2010-06-29T21:21:52.963 に答える