I have one interface with let's say 2 methods and has 3 different implementations.
public interface IFace {
public void method1(Param1 param1);
public void method2(Param2 param2);
}
public class A implements IFace {
public void method1(Param1 param1){}
public void method2(Param2 param2){}
}
public class B implements IFace {
public void method1(Param1 param1){}
public void method2(Param2 param2){}
}
public class C implements IFace {
public void method1(Param1 param1){}
public void method2(Param2 param2){}
}
Requirement: one of two methods needs modifications. Pre-conditions decide which specific implementation to call.
I need a pattern to go through those implementations one by one. This appeared like a perfect fit for chain of responsibility and I created that like this:
public interface IChain {
public void method1(Param1 param1);
public void setNextChain(IChain iChain);
}
public class AA implements IChain {
private IChain chain;
private IFace a;
public void method1(Param1 param1){
if (thisConditionIsSatisfied(param1)) {
a.method1(param1);
} else {
chain.method1();
}
}
public void setNextChain(IChain chain){
this.chain = chain
}
public void setA(IFace a) {
this.a = a;
}
}
public class BB implements IChain {
private IChain chain;
private IFace b;
public void method1(Param1 param1){
if (thisConditionIsSatisfied(param1)) {
b.method1(param1);
} else {
chain.method1();
}
}
public void setNextChain(IChain chain){
this.chain = chain
}
public void setA(IFace b) {
this.b = b;
}
}
public class CC implements IChain {
private IChain chain;
public void method1(Param1 param1){
if (thisConditionIsSatisfied(param1)) {
//process it here
} else {
throw new RuntimeException("Couldn't process request.")
}
}
public void setNextChain(IChain chain){
this.chain = chain
}
}
As you can see, CC doesn't delegate to class C which was implementing IFace and is a completely new implementation.
This is a very small part that I am displaying but the problem effectively is the same that I see a lot of duplication in terms of condition evaluation, exception handling, calling the correct implementation of the interface etc.
Though this is much better than trying to extend the existing interface but I was wondering if there is any recommendation to make it better in terms of future extensibility or OOPS pattern following.
I
for interface prefix thing you use inIFace
is a c# thing not a Java thing and certainly not a good thing. Please limit its use to c#.