design patterns how to avoid instanceOf when using List

  • A+
Category:Languages

Imagine you have a menu with dishes each dish should be available in multiple languages (French , English , Arabic , ...). The Dish class contains a list with Language type objects.

class Dish {       List<Language> languages      void addLanguage(Language lg){...} } class Language { getDescription(){}}  class French extends Language{}  class Menu {List<Dish> dishes } 

How do I avoid using instance of when wanting a description of a specific language for that dish?

Should I define for each language a get method in the dish class:getFrench(), getArabic(),..?

Or should I keep it in list and check for instance of French by looping the list and then call getDescription() on this list object<language> ?

Or is there a way for a more polymorphic approach?

 


I don't think it's a good idea to create a separate class for each language. After all, all these classes will have the exact same methods.

I'd use a single Language class, and inside the Dish class I'll keep a Map<Locale,Description> (I'd rename the Language class to something less confusing such as Description, since it doesn't represent a language, it represents a description in some language).

Now you can have a

Description getDescription(Locale locale) 

method in your Dish class, which will return the description of the dish in the language of the passed Locale.

You should prefer using standard JDK classes such as java.util.Locale instead of custom classes when possible.

After considering the comments, and agreeing to some of them, I suggest removing 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 the language specific description in a Map is more efficient than searching for it in a List (O(1) lookup time in a HashMap vs. O(n) lookup time in a List).

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: