允许特定类的实例只由Java中的另一个类创建?
作者:互联网
假设我有两个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;
}
}
我已经尝试使用Google搜索并在StackOverflow上搜索可能的解决方案,但我发现最接近的是使用带有修改的getInstance()方法的Singleton设计模式,以确保只有具有特定类型的类才能访问类的实例B.虽然这个工作得相当好,它仍然允许任何扩展A的子类来获取B的实例.有没有办法阻止这种情况发生,或者如果一个子类不能做它的超类,它会毁掉整个子类的重点能做?
解决方法:
Suppose that I have two classes A and B and I want to make it so that instances of B can only be created in A and in B itself. I don’t want any other class (including subclasses of A) to be allowed to create instances of B.
你可以使B成为A类的私有内部类.
标签:java,singleton,access-modifiers 来源: https://codeday.me/bug/20190725/1532428.html