user2080568
user2080568

Reputation: 93

Regarding changing the constructor specifier from private to protected of singleton

What would happen if we change the constructor of the singleton from private to protected? How we can prevent it breaking in that case?

Singleton:

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 ();
    }

}

For breaking the singleton the following url contains the required info cracking singleton with other ways.

Upvotes: 0

Views: 520

Answers (2)

Carlos Gavidia-Calderon
Carlos Gavidia-Calderon

Reputation: 7253

From Joshua Bloch's Effective Java on Singletons Properties:

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.

So, if you make your Singleton Constructor protected you're exposing your Constructor to let any class in the same package to make instances an instance of SingletonObject. If that happens, your Singleton Pattern is broken.

Relaxing the access modifiers of the constructor on any way -making it protected, public or default- is an open gate to instance generation, and that's not desired in a Singleton implementation.

Upvotes: 1

Torious
Torious

Reputation: 3424

Simple: Changing the constructor access modifier from private to protected allows any class in the same package to instantiate SingletonObject. We can easily create a class "in the same package" by specifying the corresponding package statement.

Edit: The answer of Carlos made me realize an additional problem that results from making the constructor protected as opposed to public: A subclass of the singleton class can be created (in another package), which can be freely instantiated and have its instance methods called; the singleton class itself no longer has full control over where and how instances (or 1 instance) are created.

Upvotes: 1

Related Questions