【发布时间】:2013-11-29 14:04:55
【问题描述】:
假设我有两个类 A 和 B,我想让它使得 B 的实例只能在 A 和 B 本身中创建。我不希望任何其他类(包括 A 的子类)被允许创建 B 的实例。在 Java 中有没有办法做到这一点?
如果不清楚我要做什么,这里有一些代码:
public class A {
B instance;
public A(){
// Still allows for subclasses to access B
instance = B.getInstance((Object)this);
}
}
这是我要限制其构造的类:
public class B {
// If I make this public all classes can create it, but
// if I make it private without any getter methods then
// no other classes but itself can create it
private B(){}
// Problem with this is that subclasses of A
// can also create instances of B
public static B getInstance(Object o){
if(o instanceof A)
return new B();
else
return null;
}
}
我已经尝试在 StackOverflow 上搜索和搜索可能的解决方案,但我发现最接近的方法是使用带有修改的 getInstance() 方法的 Singleton 设计模式,以确保只有具有特定类型的类才能访问B 类的实例。虽然这工作得很好,但它仍然使任何扩展 A 的子类都能够获取 B 的实例。有没有办法阻止这种情况发生,或者如果子类不能这样做,它会破坏子类化的全部意义它的超类能做什么?
【问题讨论】:
标签: java singleton access-modifiers