dimanche 5 février 2017

Create multiple instance of a class with different parameters

Below is my initializer class in which I am creating multiple instance of Handler class:

@Singleton
public class Initializer {
  private static final Logger logger = Logger.getInstance(Initializer.class);
  private Handler handlerA;
  private Handler handlerB;
  private Handler handlerC;
  private Handler handlerD;
  // add another handler

  private Initializer() {

  }

  @PostConstruct
  public void postInit() {
    handlerA = new Handler(Type.A, 1);
    handlerB = new Handler(Type.B, 1);
    handlerC = new Handler(Type.C, 1);
    handlerD = new Handler(Type.D, 1);
    // add another handler instance
  }

  @PreDestroy
  public void shutdown() {
    handlerA.shutdown();
    handlerB.shutdown();
    handlerC.shutdown();
    handlerD.shutdown();
    // add another handler shutdown
  }
}

And below is my Handler constructor:

  public Handler(Type type, int poolSize) {
    this.executorService = Executors.newFixedThreadPool(poolSize);
    for (int i = 0; i < poolSize; i++) {
      Loop loop = HandlerFactory.getInstance().create(type);
      loops.add(loop);
      executorService.submit(loop);
    }
  }

My question is - If I need to add another handlerE in my Initializer class, then I need to add this line:

private Handler handlerE;

And then add another line in postInit() and shutdown() method. It looks ok but I was wondering if there is any better way to write that? If I have to add 10 more handlers, then it will be a single line for all those.

Wanted to see if there is any better way to write those Handlers in my Initializer class.

Aucun commentaire:

Enregistrer un commentaire