[英]Pattern for Compositions of Abstract Objects
I have an abstract class that has an array of abstract things: 我有一个抽象类,其中包含一系列抽象的东西:
Abstract Color has abstract ColorThings[]
I have several concrete classes that each have an array of concrete things: 我有几个具体的类,每个类都有一系列具体的东西:
Concrete RedColor has concrete RedThings[]
Concrete BlueColor has concrete BlueThings[]
All are related: 所有相关:
RedColor and BlueColor are Colors.
RedThings[] and BlueThings[] are ColorThings[].
What design pattern do I need here? 我在这里需要什么设计模式? I already have a factory method going on, where any Color sub-class must be able to generate an appropriate ColorThing.
我已经在执行工厂方法,其中任何Color子类都必须能够生成适当的ColorThing。 However, I'd also like to be able to have this method in Color, which sub-classes would not need to implement:
但是,我也希望能够在Color中使用此方法,而该子类不需要实现:
addColorThing(ColorThing thing) {/*ColorThing[] gets RedThing or BlueThing*/}
Additionally, I'd like each sub-class to be able to instantiate the super.ColorThings[] as their own version of the array: 另外,我希望每个子类都可以将super.ColorThings []实例化为它们自己的数组版本:
class RedColor {
colorThings[] = new RedThings[];
}
Does Java allow for any of this? Java是否允许这一切? Can I redesign any of it better?
我可以更好地重新设计吗?
Generics will let you do what you want: 泛型可以让您做自己想做的事情:
abstract class Color<T extends ColorThings> {
protected T[] things;
}
class RedColor extends Color<RedThings> {
}
// And so on.
The idea here is that each subclass of Color
needs to declare what specific subclass of ColorThings
they use. 这里的想法是
Color
每个子类都需要声明它们使用的ColorThings
特定子类。 By using the type parameter T
, you can achieve this. 通过使用类型参数
T
,可以实现此目的。
Read more in the docs ... 阅读更多文档 ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.