I am faced with an interesting OOD problem: I have an interface with 3 methods:
interface TestInterface {
String action1();
String action2();
String action3();
}
and 3 classes that implement this interface, so I have a very simple code:
TestInterface testInt;
if(something) {
testInt = createObject1();
} else if(somethingElse) {
testInt = createObject2();
} else {
testInt = createObject3();
}
if(againSomething) {
testInt.action1();
} else if(againSomethingElse) {
testInt.action2();
} else {
testInt.action3();
}
This works fine, however I need to add additional action, but this action only makes sense in the context of one of the classes that implement TestInterface and not in the other two, so if I would to continue the pattern, I would have to add it to the interface, and make a dummy implementation in other classes, but at least the rest of the code would look nice:
interface TestInterface {
String action1();
String action2();
String action3();
String action4();
}
...
if(someSpecificAction) {
testInt.action4();
}
I'm not quite keen on that kind of design, so I'm looking for an alternative. I was thinking about creating another interface, just with that method, but I was wondering if I can do better than this code below ?
interface TestInterface {
String action1();
String action2();
String action3();
}
interface NewInterface {
String action4();
}
TestInterface testInt;
if(something) {
testInt = createObject1();
} else if(somethingElse) {
testInt = createObject2();
} else if(something3) {
testInt = createObject3();
} else {
testInt = createObject3();
}
if(againSomething) {
testInt.action1();
} else if(againSomethingElse) {
testInt.action2();
} else if(something) {
testInt.action3();
} else {
NewInterface newI = (NewInterface)testInt;
newI.action4();
}
Is there a better way to solve this problem ?