java - reduce number of cases from a switch -


i have following piece of code. it's kind of factory function retrieves instance of writer base on it's type. notice type enum.

public writer getwriter(writertypeenum type){   switch(type){     case a: new awriter() break;     case b: ... break;     case c: ... break;     ...   } } 

the problem have 30 cases. can reduce them or not implement them @ all?

i solved cases in past using strategy pattern here facing old enum used in entire app. other problem cannot inject spring beans enum. of instances switch cases beans.

the writertypeenum has id coming ui , based on id have determine right instance.

you can setup enum have abstract method

public abstract writer getwriter(); 

and after that, instances have implement method, example

public enum yourenum{     first(){         public writer getwriter(){             return null;         }     }, ... // other enums      public abstract writer getwriter();  } 

or omit break in switch, if there repeating statements


Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -