开发者

Is it possible to have an enum that contains constructors for objects?

开发者 https://www.devze.com 2023-03-18 05:29 出处:网络
I\'m testing out a different sort of pattern.I\'ve already got the code working in a switch statement, but I\'d like to try something a little more ecclectic... for research purposes.

I'm testing out a different sort of pattern. I've already got the code working in a switch statement, but I'd like to try something a little more ecclectic... for research purposes.

Say I have 4 classes, Class1, Class2, Class3, and Class4 that all extend BaseClass. I want to put them into an enum, like 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;
    try {
      b = (BaseClass)this.factory.newInstance();
    } catch (Exception e) {
      // handle any exceptions
    }
    return f;
  }
}

In a factory method that is passed an int, I want to be able to do something like this:

public void fakeMethod(int type) {
  BaseClass someClass = ClassFactories.values()[type].generate();
  someClass.doStuff();
}

Is there a cleaner/easier way of doing this? I'm not so much con开发者_运维百科cerned with readability (right now), I'm just curious if this is possible.


Yes, this is possible. Something like a 'Template Method' approach. So for 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 {
   for (ClassFactory s : EnumSet.allOf(ClassFactory.class))
         lookup.put(s.getIntValue(), s);
   }

   public static ClassFactory getValue(int intValue) {
      return lookup.get(intValue);
   }

}

INVOCATION CODE

With the use of static imports, the client code calling this enumeration would look like:

Class1.generate();
Class2.generate();
//or better...
getClass().generate();

Or

public void fakeMethod(int type) {
  ClassFactory.getValue(type).generate();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消