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 case
s. 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 bean
s.
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
Post a Comment