Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I create protected constructor for my singleton classes?

By design, in Singleton pattern the constructor should be marked private and provide a creational method retuning the private static member of the same type instance. I have created my singleton classes like this only.

public class SingletonPattern {// singleton class

    private static SingletonPattern pattern = new SingletonPattern();

    private SingletonPattern() {

    }

    public static SingletonPattern getInstance() {
        return pattern;
    }

}

Now, I have got to extend a singleton class to add new behaviors. But the private constructor is not letting be define the child class. I was thinking to change the default constructor to protected constructor for the singleton base class.

What can be problems, if I define my constructors to be protected?

Looking for expert views....

like image 483
Vijay Shanker Dubey Avatar asked Jan 20 '23 23:01

Vijay Shanker Dubey


1 Answers

If you extend a singleton class via inheritance, you'll have 2 instances of the singleton class running around should someone grab your singleton and the original singleton.

If the original singleton is conceptually really supposed to be a singleton, then using composition is probably the way to go. However, then substitutability is lost (your class is not substitutable for the original singleton; it just uses it).

Do you have a concrete example?

like image 73
lijie Avatar answered Jan 30 '23 19:01

lijie