如何围绕已经存在但无法在Java中修改的类创建接口 [英] how to create an interface around classes that already exist but cannot be modified in java

查看:105
本文介绍了如何围绕已经存在但无法在Java中修改的类创建接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我的代码中已经有2个类:

Suppose I already have 2 classes in my code:

class SomeOrder {
  String getOrderId() { return orderId; }
}

class AnotherOrder {
  String getOrderId() { return orderId; }
}

如何围绕这两个类创建接口:

How to create an interface around both these classes which is:

interface Order {
    String getOrderId();
}

理想情况下,我会修改代码,使 SomOrder实现Order AnotherOrder实现Order ,但是这里的问题是它们属于我无法控制或编辑的包(即它们来自外部jar)。

Ideally, I would modify the code so that SomOrder implements Order and AnotherOrder implements Order but the catch here is that they belong in a package that I cannot control or edit (i.e. they come from an external jar).

我的算法当前如下所示:

My algorithm currently looks like this:

void sorter(List<SomeOrder> orders) {
    ... <custom sort logic> ...
    someOrder.getOrderId();
}

void sorter(List<AnotherOrder> orders) {
    ... <custom sort logic> ...
    someOrder.getOrderId();
}

使用单个界面,我可以编写:

With a single interface I can write:

void sorter(List<Order> orders) {
        ... <custom sort logic> ...
        order.getOrderId();
}


推荐答案

您可以使用适配器类:

You can use adapter classes:

class SomeOrderAdapter implements Order {
    private SomeOrder delegate;

    @Override
    public String getOrderId() {
        return delegate.getOrderId();
    }
}

类似,对于 AnotherOrder

这篇关于如何围绕已经存在但无法在Java中修改的类创建接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆