java - Is it possible to have an enum that contains constructors for objects? -
java - Is it possible to have an enum that contains constructors for objects? -
i'm testing out different sort of pattern. i've got code working in switch
statement, i'd seek little more ecclectic... research purposes.
say have 4 classes, class1
, class2
, class3
, , class4
extend baseclass
. want set them enum
, so:
enum classfactories { class1(class1.class), class2(class2.class), class3(class3.class), class4(class4.class); private final class factory; classfactories(class factory) { this.factory = factory; } public baseclass generate() { baseclass b = null; seek { b = (baseclass)this.factory.newinstance(); } grab (exception e) { // handle exceptions } homecoming f; } }
in mill method passed int
, want able this:
public void fakemethod(int type) { baseclass someclass = classfactories.values()[type].generate(); someclass.dostuff(); }
is there cleaner/easier way of doing this? i'm not much concerned readability (right now), i'm curious if possible.
yes, possible. 'template method' approach. example
public enum classfactory { class1() { @override public void generate() { system.out.println("i'm in class 1."); } }, class2() { @override public void generate() { system.out.println("i'm in class 2."); } }; //template method public abstract void generate(); private static final map<integer, classfactory > lookup = new hashmap<integer, classfactory >(); static { (classfactory s : enumset.allof(classfactory.class)) lookup.put(s.getintvalue(), s); } public static classfactory getvalue(int intvalue) { homecoming lookup.get(intvalue); } }
invocation code with utilize of static imports, client code calling enumeration like:
class1.generate(); class2.generate(); //or better... getclass().generate();
or
public void fakemethod(int type) { classfactory.getvalue(type).generate(); }
java enums constructor
Comments
Post a Comment