samedi 24 décembre 2016

Better way to return a new instance of Process

I have a below factory which will get called from multiple threads.

public class ProviderFactory {
  private final Map<TypeName, Provider> typeToProvidersMap;

  private static class Holder {
    private static final ProviderFactory INSTANCE = new ProviderFactory();
  }

  public static ProviderFactory getInstance() {
    return Holder.INSTANCE;
  }

  private ProviderFactory() {
    Map<TypeName, Provider> tmp = new HashMap<>();
    typeToProvidersMap.put(TypeName.typeA, new DataProvider());
    typeToProvidersMap.put(TypeName.typeB, new ProcessProvider());

    this.typeToProvidersMap = Collections.unmodifiableMap(tmp);
  }

  public IProcess createNewProvider(TypeName typeName) {
    Provider provider = typeToProvidersMap.get(typeName);
    if (provider == null) {
      throw new IllegalArgumentException("invalid typeName is passed");
    }
    IProcess process = new ProcessImpl(typeName.name(), provider);
    return process;
  }
}

In my above factory createNewProvider method will be called from multiple threads. It looks like there is no need to use the Holder pattern in such a convoluted way the way I am doing right now? For instance, I am using inner class just to hold the instance that I immediately construct?

Is it ok to use factory pattern here the way I am using right now or is there any other better and simple way to do the same thing which is also thread safe?

Aucun commentaire:

Enregistrer un commentaire