I have trouble understanding when multiple classes implements same interface, before i was using concrete classes as DI but after searching and reading i was told that it should depend on abstaraction.So this is my problem:
interface SomeInterface{
public void doSomething();
}
We have two classes that implements interface:
class FirstClass implements SomeInterface{
@Override
public void doSomething(){
System.out.print("First class is doing something");
}
}
class SecondClass implements SomeInterface {
@Override
public void doSomething() {
System.out.print("Second class is doing something");
}
}
And now i have a client where i want to use method from First and Second class:
class ClientClass {
private SomeInterface someInterface;
public ClientClass(SomeInterface someInterface) {
this.someInterface = someInterface;
}
public void testMethod() {
this.someInterface.doSomething();
}
}
Now when i instantiate Client class i can only pass one class in constructor either first or second, and that method will start, but what if i want both method? What is wrong with this design?
ClientClassand calltestMethodsindependently or use design patterns like Composite in other casesSomeInterfaceat a time. If you need exactly two of them, you could use 2 member variables, and expect 2 arguments in the constructor. However if you need any amount of them, someListor perhapsSetwould be a better way, and later you might need altering the collection ofSomeInterfaces outside the constructor too.