Java – should I create a protected constructor for my singleton class?
According to the design, in singleton mode, the constructor should be marked as private and provide the creation method of rebuilding private static members of instances of the same type I only created such a singleton class
public class SingletonPattern {// singleton class private static SingletonPattern pattern = new SingletonPattern(); private SingletonPattern() { } public static SingletonPattern getInstance() { return pattern; } }
Now I have to extend a singleton class to add new behavior But private constructors do not allow subclasses to be defined I'm considering changing the default constructor to a protected constructor of a singleton base class
What might happen if I defined the constructor as protected?
Looking for expert advice
Solution
If you extend the singleton class through inheritance, if someone catches your singleton and the original singleton, you will have two instances of the singleton class running
If the original single should be single in concept, then using composition may be the way to go However, substitutability is lost (your class cannot replace the original Singleton; it just uses it)
Do you have a specific example?