Reputation: 1444
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 implementation2
and 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
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
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
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