我有一个界面:
public interface Service {
default Type service1(Type t) throws IOException {
throw new UnsupportedOperationException();
}
default Type service2(Type t) throws IOException {
throw new UnsupportedOperationException();
}
}
以及一个实现该接口(interface)但只需要service2的类:
class MyService implements Service{
@Override
Type service2(Type t) throws IOException {
...
}
}
然后我创建一个 myservice-instance:
Service s = new MyService();
s.service1(t); // throws error at runtime
是否有更好的方法来隐藏或标记 service1() 方法,以表明没有人应该在代码中使用此不受支持的方法(例如,通过注释?)。或者我是否必须为这种情况创建另一种模式?
最佳答案
Service
接口(interface)(根据您的描述)明显违反了接口(interface)隔离原则 ( ISP )。您应该有两个接口(interface):Service1
和 Service2
。如果您需要聚合,可以通过名为 AggregateService
的接口(interface)获取它,该接口(interface)将扩展 Service1
和 Service2
。
根据您当前的设计,不可能仅对外部系统隐藏一种方法。
关于java - 如何从类中隐藏不支持的接口(interface)方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55544037/