Reputation: 16143
Say, we have a superclass Car
and two subclasses Ford
and Porsche
. Now an graphical user interface should display a proper representation (e.g. the name of the Car). We could add an additional method getCarName()
to each subclass.
But now, we have another GUI which wants to represent the cars by some other property, e.g. the car name plus production country. We then have to add another method, and so on.
Generally spoken, I want to store some kind of configuration/property in a nice way. The original data structure (with perhaps a lot of subclasses) should not be changed each time another representation is wanted. So I thought of creating a HashMap which associates the subclasses to its property and hand this HashMap to the GUI.
But what kind of key should be used ? HashMap<Car, String>
is no solution because I do not want to create objects of cars just to store the representation. The String representation is independent of an instance.
Desing patterns are welcome, too.
Upvotes: 0
Views: 124
Reputation: 75
You can store all the properties/attributes of any car in a POJO(eg: CarPropertyPOJO) and then use this POJO to display which ever attributes you need. This could be uniformly used across you different pages. As per your question CarPropertyPOJO would contain 2 member variable carName and productionCountry. In a case you just want to display a property of a single car then just passing a CarPropertyPOJO object to UI would solve the problem. And suppose you wanna display properties of many cars in a tabular form then you can pass a Collection object (ArrayList<CarPropertyPOJO> or a HashMap). CarSubClassName could just signify the subClass of the car.
Upvotes: 1
Reputation: 8318
To have a clean design, I would rather prefer to have a method like getProductionCountries
in the Car
class and that can be overridden by each subclass. When you add a new car, you do need to write more code, but that is rather unavoidable.
Upvotes: 0