如果我们将单例的构造函数从私有(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/