When and why does the Child class declare a static member of an instance of the parent class?

This is another design pattern in some legacy code that I could not find on Google. In this case, the child class extends its abstract parent element, but then rotates to the right and declares a static instance of the parent:

public abstract class MessageBase {
    protected DAOFactory factory;
    // method declarations
}

public class EDWMessage extends MessageBase {
    private static MessageBase instance;

    public static MessageBase getInstance(Properties properties) {
        if (instance == null) {
            instance = new EDWMessageTransaction(properties, null);
        }
        return instance;
    }
//more code
}

I'm not sure I understand what will drive this design pattern (if it's a known pattern). Is this a kind of convenience model to avoid declaring each parent member variable as static? Or it means that for each of several child classes there is one parent instance. But if so, why the overuse of inheritance over simple composition?

, . . !

P.S. , , , . , .

: . , , . Yay .

+3
2

. , .

public class MySingleton{

   private MySingleton(){

   }

   public static MySingleton getInstance(){
       return SingletonCreator.INSTANCE;
   }

   private static class SingletonCreator{
     private static final MySingleton INSTNACE = new MySingleton();
   }
}

, , ,

+3

, MessageBase , commom

2cents

0

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


All Articles