Should I create a protected constructor for my singleton classes?

By design, in the template, the Singletonconstructor should be marked private and provide a creation method that reconfigures the private static member of the instance of the same type. I created only my singleton classes.

public class SingletonPattern {// singleton class

    private static SingletonPattern pattern = new SingletonPattern();

    private SingletonPattern() {

    }

    public static SingletonPattern getInstance() {
        return pattern;
    }

}

Now I need to extend a singleton class to add new behavior. But the private constructor does not allow to define a child class. I was thinking of changing the default constructor for the protected constructor for the singleton base class.

What could be the problem if I determine what my constructors are protected?

Seek expert opinions ....

+3
4

, 2 , - .

, , , . , ( , ).

?

+6

, . , , .

+1

Singleton Class. , getInstance() static n , n , Singleton Pattern. Singleton, , getInstance(). , . , - , , , , .

public class SingletonPattern {// singleton class

private static SingletonPattern pattern = new SingletonPattern();

private SingletonPattern() {

}

public static SingletonPattern getInstance() {
    if(SingletonPattern == null) {
        return new SingletonPattern();
    }
}
0

, , , - .

You can create a protected constructor in a singleton class. If you want to have polymorphic behavior on your Singleton, you can make it an abstract class, set the constructor for protection, and delegate the creation of the instance to one of the specific subclasses.

I found the following example in the book "Design Patterns":

abstract public class Tax{
    static private Tax instance;

    protected Tax() {};

    abstract double calcTax( double qty, double price);

    public static Tax getInstance() {
      // code to determine what implementing class to use
      instance = USTax.getInstance();
      return instance;
    }
 }

public class USTax extends Tax {
     private static USTax instance;
     private USTax() {  
   // instantation local members +  Tax abstract class
 }

 public double calcTax ( double qty, double price){
   // implementation
 }

 public static Tax getInstance() {
     if(instance == null) 
        instance = new USTax();
     return instance;
  }
 }
0
source

Source: https://habr.com/ru/post/1779089/


All Articles