代码之家  ›  专栏  ›  技术社区  ›  RobinFrcd

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

  •  0
  • RobinFrcd  · 技术社区  · 6 年前

    我在用一些课程 无法修改 以下内容:

    • 将军请求
    • specificrequest1(扩展genericrequest)
    • specificrequest2(扩展genericrequest)

    这两个特定的请求类共享很多方法(但这些方法没有在genericrequest中声明,我知道这很糟糕,但我只是无法更改)。

    我想创建一个类似这样的方法(尽可能地分解):

    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();
    }
    

    我知道这不是有效的Java,但这就是我的想法。你觉得用这个可以干点什么吗?或者我必须创建两种不同的方法来处理这两种情况 SpecificRequest1 SpecificRequest2 是吗?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Alexey Rykhalskiy    6 年前

    这是一个众所周知的模式适配器。代码可能如下所示:

    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());
        }
    }
    

    尽量避免在方法参数和 instanceof 不惜一切代价)