我遇到了有关 java 8 中公共(public)接口(interface)模拟的问题。 我现在有这个方法的接口(interface):
public interface A<T> {
void method1(T t) throws someException;
void method2(T t) throws someException;
default method3() {
return Collections.emptyMap();
}
}
接口(interface)A由类B
实现,它是一个抽象类:
public abstract class B<T> implements A<T> {
@Override
public void method1(T type) throws someException {
// (.... some code snipets ....)
}
}
method1
包含所有逻辑,并且应该是开发人员可以看到/使用的逻辑。
现在,下面是类B
的具体表示:
public final class ConcreteB extends B<someObject> {
private static ConcreteB concreteBInstance = null;
private ConcreteB() {
}
public static ConcreteB getInstance() {
if (concreteBInstance == null) {
concreteBInstance = new ConcreteB();
}
return concreteBInstance;
}
@Override
public void method2(someObject someObject) throws someException {
// (... code ...)
}
}
总而言之,B 的具体实现实现了方法 2(如果用户愿意,还可以实现方法 3)。类 B 实现了 method1
,其中包含所有逻辑。
我的问题是,当我执行ConcreteB.getInstance()
时,开发人员可以使用的方法是method1
、method2
和 method3
,我想让开发人员仅看到 method1。但是因为 java 8 不允许我在接口(interface)上创建私有(private)方法,所以我不知道该怎么做。
有什么办法可以解决这个问题吗?
谢谢!
最佳答案
你不应该把那些“私有(private)”方法放在接口(interface)中。接口(interface)将强制 B
及其所有子类的公共(public) API 向世界公开所有三个方法。这是因为接口(interface)旨在定义公共(public) API。
在这种情况下,您可以做的是将所有方法从接口(interface)移至 B
(method1
除外):
public interface A <T> {
void method1(T t) throws someException;
}
public abstract class B<T> implements A<T> {
protected abstract void method2(T t) throws someException;
protected method3() {
return Collections.emptyMap();
}
@Override
public void method1(T type) throws someException {
(.... some code snipets ....)
}
}
这样,您就可以在公共(public) API 中仅包含您想要包含在其中的方法,而其余的仅可用于 B 及其子类。如果 B
的子类不应该访问其他两个方法,那么您可以在 B
中将它们设置为私有(private)。
此外,如果您想防止 B
的子类重写 method1
,您可以将其声明为 final
。
关于java - 在java 8中模拟私有(private)接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60507173/