ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

允许特定类的实例只由Java中的另一个类创建?

2019-07-25 11:03:43  阅读:313  来源: 互联网

标签: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. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有