标签:java singleton access-modifiers
假设我有两个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
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。