3

This is another design pattern in some legacy code that I couldn't find much about on google. In this case a child class extends its abstract parent, but then turns right around 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 would drive this design pattern (if it is a known pattern). Is this a sort of convenience pattern to avoid declaring each member variable of the parent as static? Or is it meant to allow multiple children classes to each have one instance of the parent. But if that's the case, why the excessive use of inheritance over just plain composition?

The rest of the code gives no indication as to why it would be done this way. Any thoughts or ideas would be much appreciated. Thanks!

P.S. I seem to be running in to a lot of interesting design patterns in this legacy code that I don't know how to handle. Thanks to everyone who has helped me out already.

Edit: Expanding the code sample. Will edit again as I discover someplace that actually uses this code. Yay for no documentation.

Community
  • 1
  • 1
Riggy
  • 1,347
  • 1
  • 14
  • 26

2 Answers2

3

This is a common idiom for thread-safe lazy singleton initialization. If you can have a singleton class, you delegate to a private static instantiating class.

public class MySingleton{

   private MySingleton(){

   }

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

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

Not sure if this is how your child class is being used, but this would be a use case for a child class holding a static instance of its parent

John Vint
  • 39,695
  • 7
  • 78
  • 108
  • +1: The explanation makes some sense, except you're using composition, not inheritance for your example. I assume that doesn't invalidate the reasoning though. I will extend the sample code I included to see if that alters the answer at all. Thanks! – Riggy Dec 14 '10 at 21:08
0

The original intent probably was that for each subclass of MessageBase there should only be 1 instance and that you can access that instance with a commom method in the base class

so you could iterate over all message types and get the instance of each

my 2cents

Liviu T.
  • 23,584
  • 10
  • 62
  • 58