我有一个抽象类,其中包含一系列抽象的东西:

Abstract Color has abstract ColorThings[]


我有几个具体的类,每个类都有一系列具体的东西:

Concrete RedColor has concrete RedThings[]
Concrete BlueColor has concrete BlueThings[]


所有相关:

RedColor and BlueColor are Colors.
RedThings[] and BlueThings[] are ColorThings[].


我在这里需要什么设计模式?我已经在执行工厂方法,其中任何Color子类都必须能够生成适当的ColorThing。但是,我也希望能够在Color中使用此方法,而该子类无需实现:

addColorThing(ColorThing thing) {/*ColorThing[] gets RedThing or BlueThing*/}


另外,我希望每个子类都可以将super.ColorThings []实例化为它们自己的数组版本:

class RedColor {
    colorThings[] = new RedThings[];
}


Java是否允许这一切?我可以更好地重新设计它吗?

最佳答案

泛型将让您做自己想做的事情:

abstract class Color<T extends ColorThings> {
    protected T[] things;
}

class RedColor extends Color<RedThings> {
}

// And so on.


这里的想法是Color的每个子类都需要声明它们使用的ColorThings特定子类。通过使用类型参数T,可以实现此目的。

Read more in the docs ...

10-04 18:56