java - 关于将单例的构造函数说明符从 private 更改为 protected

标签 java design-patterns

如果我们将单例的构造函数从私有(private)更改为 protected ,会发生什么?在这种情况下我们如何防止它破裂?

单例:

public class SingletonObject
{
    private static SingletonObject ref;

    private SingletonObject () //private constructor
    {
        System.setSecurityManager(new SecurityManager());
    }

    public  static synchronized   SingletonObject getSingletonObject()
    {
        if (ref == null)
            ref = new SingletonObject();
                return ref;
    }   

    public Object clone() throws CloneNotSupportedException
    {
        throw new CloneNotSupportedException ();
    }

}

为了打破单例,以下网址包含所需的信息 cracking singleton with other ways .

最佳答案

来自Joshua Bloch's Effective Java关于单例属性:

The private constructor is called only once, to initialize the public static final field (...). The lack of public or protected constructors guarantees a “monoinstance” universe: Exactly one (...) instance will exist once the Singleton class is initialized—no more, no less. Nothing that a client does can change this.

因此,如果您将 Singleton 构造函数设置为 protected ,那么您将公开您的构造函数,以便让同一包中的任何类将实例设为 SingletonObject 的实例。如果发生这种情况,你的单例模式就被破坏了。

以任何方式放宽构造函数的访问修饰符(使其 protected 、公开或默认)都是实例生成的大门,这在单例实现中是不希望的。

关于java - 关于将单例的构造函数说明符从 private 更改为 protected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14985519/

相关文章:

javascript - AngularJS Controller ,DRY 代码的设计模式

c# - 如何高效地创建和使用 builder 模式

c++11 - 整理 C++ 运算符重载

Java - 如何将计算语句结果四舍五入到两位有效数字

java - Android TV ImageCardView 标题换行

java - 我们可以访问webview中的元素并填充 block 并使其自动点击提交吗

java - 在运行时访问对象!

java - 如何检查 Java 中 Long range 之外存在的范围?

java - 知道这个错误在 SVN 中意味着什么吗?

c# - 哪种设计模式最适合足球比赛应用程序