title: Observer pattern and DAO classes with CRUD static methods
body: <p>I'm reviewing some DAO classes where they are exposing CRUD static methods create(), delete() etc etc. to the program and where each DAO class implements the Observer pattern by checking for changes in the database through the Notification.java class and if one change notification is received by pulling the Object from database.</p>
  
  <p>The simplified code is similar to this:</p>
  
  <p>OfficeDAO.java</p>
  
  <pre><code>public class OfficeDAO implements PropertyChangeListener
  {
      public OfficeDAO()
      {
          /* 
           * Below we add ourselves to the observers of class Notifications
           * (see observer pattern in Java) in practice we are notified
           * when one of our objects is changed by a remote client user
           */
          Notification.addChangeListener(this);
      }
  
      public static void create(Office office)
      {
        Connection connection = DBConnection.getConnection();
  
        //... stuff with the database insertion
  
        Notification.notifyDatabaseChanges("ocreate-" + officeId);
      }
  }
  </code></pre>
  
  <p>Now the problem is that the addChangeListener(this); is in the constructor but because this DAO class is used through its static methods the constructor is never called.</p>
  
  <p>To fix this in the main() method of the application (inside the EDT thread by the way) there's a call like:</p>
  
  <pre><code>new OfficeDAO(); //ignore this, it is needed only to start the DAO constructor
  </code></pre>
  
  <p>This seemed quite hacky so I thought adding a</p>
  
  <pre><code>static {
    Notification.addChangeListener(this);
  }
  </code></pre>
  
  <p>in the OfficeDAO.java class but of course the "this" reference is not present in a static initializer, so I'm out of solutions.
  Removing the static from DAO methods is out of questions because these methods are called all over the application and are called without an instance of the class.</p>
  
  <p>Is there any clean solution or workaround that I'm currently missing?</p>