Tell a class on creation the type of a member variable

Viewed 56

Suppose I have a CityDistrict class as follows:

class CityDistrict {
    List<House> houses;
    ...
}

Suppose for some usecases an ArrayList would be the better fit for houses and sometimes an LinkedList for example. How would you tell the CityDistrict on creation what class it should use for houses

My three ideas are:

1) Is this a usecase for parametric classes? Something like

class CityDistrict<T> {
    T<House> houses;
    ...
}

Then you could create a CityDistrict<ArrayList>. But I suppose the information that T should be of the type List is lost here.

2) Or you could create several Constructors or static factory methods like generateArrayListCityDistrict but this is kind of ugly I think.

3) Use some kind of flag variable in the constructor CityDistrict(int ListFlag) and map 1 to ArrayList and so forth. Also kind of ugly I think.

Am I missing the obvious here? What would be a clean and OOP way of handling this situation?

1 Answers
Related