Reputation: 5486
I'm using some classes that I can't modify:
Both of the SpecificRequest classes share a lot of method (but these method are not declared in GenericRequest, I know this is bad but I just can't change this).
I would like to create a method like this one (to factorize as much as possible):
private void fillRequest( GenericRequest p_request, boolean p_specificModeOne ) {
if( p_specificModeOne ) {
SpecificRequest1 l_specificRequest = (SpecificRequest1) p_request;
}
else {
SpecificRequest2 l_specificRequest = (SpecificRequest2) p_request;
}
l_specificRequest.commonMethod1();
l_specificRequest.commonMethod2();
}
I know this is not valid Java, but that is the idea. Do you think it would be possible to do something clean with this ? Or I have to create two different methods to handle both SpecificRequest1
and SpecificRequest2
?
Upvotes: 0
Views: 104
Reputation: 418
This is a well-known pattern Adapter. The code could look like this:
class GenericRequest {}
class SpecificRequest1 extends GenericRequest {
void method1() {
System.out.println("specific1");
}
}
class SpecificRequest2 extends GenericRequest {
void method2() {
System.out.println("specific2");
}
}
interface ReqInterface {
void method();
}
class Specific1 implements ReqInterface {
private final SpecificRequest1 req =new SpecificRequest1();
@Override
public void method() {
req.method1();
}
}
class Specific2 implements ReqInterface {
private final SpecificRequest2 req =new SpecificRequest2();
@Override
public void method() {
req.method2();
}
}
public class Production {
void method(ReqInterface req) {
req.method();
}
public static void main(String[] args) {
Production l3 = new Production();
l3.method(new Specific1());
l3.method(new Specific2());
}
}
Try to avoid any booleans in method parameters and instanceof
at any cost ))
Upvotes: 2