nguyentt
nguyentt

Reputation: 669

Combine Inheritance and Composition - Design Pattern

Sorry for the unclear Title. I have a following scenario:

I have 4 types: Type1, Type2, Type3, Type4. (which have same structure: name and children)

I have other 4 types of children: Child1, Child2, Child3, Child4. (which in turn have the same structure: parent and value).

Condition: Type1 can have only children of type: Child1; Type2->child2 and so on.

If I use Inheritance for this case: all of types inheritate from SuperType and all of children inheritate from Children.

public class Children {

}

public class SuperType {
    private List<Children> children;
}

public class Type1 extends SuperType {

}

public class Child1 extends Children {

}

Type1 can have children from Child2, Child3, Child4. That's not what I want.

Do you have any idea about pattern designs which I could use for this case?

Upvotes: 0

Views: 253

Answers (1)

ernest_k
ernest_k

Reputation: 45339

You can solve it by making SuperType generic and using a type parameter for Children:

public class SuperType<T extends Children> {
    private List<T> children;
}

And then subclasses will specify their own type of Children:

public class Type1 extends SupperType<Child1>{}
public class Type2 extends SupperType<Child2>{}

All you'll have to do then is make the API of SuperType use the type parameter.

Upvotes: 4

Related Questions