zer0Id0l
zer0Id0l

Reputation: 1444

Calling different implementation of a class

I have 2 different implementation of a interface KafkaMetricsReporter name it implementation1 and implementation2. Each of the implementation has start method which starts few threads.

From another class I have to instantiate both implementation1 and implementation2and then run start methods of each class. Although I can do it one by one in the given class but is there any cleaner way to do this, so that in future if I have to add one more implementation it would be be easier to do so. Please give me some pointers.

Correction: KafkaMetricsReporter is an interface

Upvotes: 1

Views: 594

Answers (3)

Suresh Atta
Suresh Atta

Reputation: 121998

There is a cleaner and traditional way. That is Programming with Interfaces.

Make an interface with start() method and let the other two classes implement it.

Edit: If it an interface, you are almost and a small code needed. Put all the references in an List/Array/Any container.

Just loop on them

for( KafkaMetricsReporter  kmr : yourListorArray){
          kmr.start(); 
}

That call's all instances start method.

Upvotes: 2

mxb
mxb

Reputation: 3330

In the client code you can reference the interface directly. For example:

public class Impl1 implements KafkaMetricsReporter {
 //...
}
public class Impl2 implements KafkaMetricsReporter {
}

class Client {
  public method() {
    KafkaMetricsReporter reporter1 = new Impl1();
    KafkaMetricsReporter reporter2 = new Impl2();

    reporter1.start();
    reporter2.start();
  }
}

Upvotes: 0

laune
laune

Reputation: 31290

Is this what you were looking for? Not sure whether I understood the Q.

KafkaMetricsReporter[] kmrs = new KafkaMetricsReporter[]{
    new implementation1(),
    new implementation2()
};

for( KafkaMetricsReporter kmr: kmrs ){
    kmr.start();
}

Upvotes: 5

Related Questions