Java – how to avoid instanceof when using list in design pattern
Imagine that you have a menu and each dish should be in multiple languages (French, English, Arabic...) The dish class contains a list of language type objects
class Dish { List<Language> languages void addLanguage(Language lg){...} } class Language { getDescription(){}} class French extends Language{} class Menu {List<Dish> dishes }
If I want to describe the dish in a specific language, how can I avoid using it?
I should define a get method in a class for each language: getfrench(), getarabic()?
Or should I keep it in the list, check the instance of French through the circular list, and then call getdescription() < language > on this list object?
Or are there more polymorphic methods?
Solution
I don't think it's a good idea to create a separate class for each language After all, all these classes will have exactly the same methods
I will use a single language class. In dish class, I will keep map < locale, description > (I rename the language class to something less confusing, such as description, because it does not represent a language, it represents a description of a language)
Now you can have one
Description getDescription(Locale locale)
The method in your dish class, which will return the description of the dish in the passed locale language
Where possible, you should prefer to use standard JDK classes, such as Java util. Locale instead of custom class
After considering these comments and agreeing with some of them, I suggest deleting the map to the description class
class Dish { Description description = new Description (); void addDescription(Locale locale,String text) { description.addText(locale,text); } String getDescription(Locale locale) { return description.getText(locale); } } class Description { Map<Locale,String> descriptions = new HashMap<>(); public void addText(Locale locale,String text) { descriptions.put(locale,text); } public void getText(Locale locale) { return descriptions.get(locale); } }
You should also note that searching for a language specific description in map is more effective than searching for it in list (O (1) lookup time in HashMap is compared with O (n) lookup time in list)