Use enum to create thead-safe factory instances

Viewed 79

I write the code for creating multiple instances for the thread-safe factory creation:

public class XWebserviceObjectFactoryCreator {
    
}

However, the code looks repeating to me and not happy about it. Is it possible to use enum (or something else) to make it more readable?

2 Answers

Since the example shows all the classes have no-argument constructors, you can use the Class.newInstance method, so something like :

private static Map<Class<?>, Object> instances = new HashMap<>();

public static <T extends Object> T getObjectFactoryInstance(Class<T> clazz)  {
    
    Object result;

    if ((result = instances.get(clazz)) == null) {                
            synchronized (instances) {

            if ((result = instances.get(clazz)) == null) { 
                 try {
                       result = clazz.newInstance();
                       instances.put(clazz, result)
                   } catch (InstantiationException |  IllegalAccessException e) {
                         // do something
                    }
              }
         }
    }

    return (T)result;
  }

Apologies if layout or syntax is off, but I’m away from my computer and doing this on the phone - but hope you get the idea !

If any classes do require arguments in their constructors, then you’ll have to use reflection to invoke the constructor.

Finally, note that I’ve modified the declaration of clazz from Class<?> to Class< T>, to let the generics validate the caller by tying the output to the given Class.

you can use the Abstract Factory design Pattern along with Enum where Sales2ObjectFactory, OrderingObjectFactory, Settings2ObjectFactory, and SettingsObjectFactory can be a factory in itself with a common interface.

Then you can use Enum to get the instance of one of those factories.

public static class FactoryMaker {

  public enum FactoryType {
    SALES2OBJECT, ORDERING,SETTING2OBJECT,SETTINGS
  }

  public static CommonFactory makeFactory(FactoryType type) {
    switch (type) {
      case SALES2OBJECT:
        return new Sales2ObjectFactory();
      case ORDERING:
        return new OrderingObjectFactory();
      case SETTING2OBJECT:
         return new Settings2ObjectFactory();
      case SETTINGS:
          return new new SettingsObjectFactory();
      default:
        throw new IllegalArgumentException("FactoryType not supported.");
    }
  }
}

Please check :: https://java-design-patterns.com/patterns/abstract-factory/

Related