Pattern for Compositions of Abstract Objects

42 views Asked by At

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. However, I'd also like to be able to have this method in Color, which sub-classes would not need to implement:

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:

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

Does Java allow for any of this? Can I redesign any of it better?

1

There are 1 answers

1
Christophe Biocca On BEST ANSWER

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. By using the type parameter T, you can achieve this.

Read more in the docs...