简体   繁体   English

调用两个不同类的相同方法

[英]Call same method of two different classes

I'm using some classes that I can't modify : 我正在使用一些无法修改的类

  • GenericRequest 通用请求
  • SpecificRequest1 (extends GenericRequest) SpecificRequest1(扩展GenericRequest)
  • SpecificRequest2 (extends GenericRequest) SpecificRequest2(扩展GenericRequest)

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). 这两个SpecificRequest类都共享许多方法(但是这些方法未在GenericRequest中声明,我知道这很不好,但是我无法更改)。

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. 我知道这不是有效的Java,但这就是想法。 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 ? 还是我必须创建两个不同的方法来处理SpecificRequest1SpecificRequest2

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 )) 尝试不惜一切代价避免方法参数和instanceof中的布尔值))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM