Home > Articles > Programming > Java

  • Print
  • + Share This
Like this article? We recommend

Observers

An observer is just an interested party; that is, an object with a vested interest in the value of some piece of data maintained by the publisher (i.e., the object observerGui).

Bear in mind that in the present case there is just one item of data maintained by the publisher—we use this pattern precisely because we want just one instance of the data. There is another design pattern called the singleton that is conceptually similar but it provides just one instance of a given object.

In other words, when you have a given singleton class X, you know for sure that there will only be one instance of that class.

One important aspect of design patterns is the interrelationships between them—each pattern has its own special purpose, and combining patterns can yield powerful solutions.

Listing 2 illustrates the Observable interface.

Listing 2 Observable interface

public interface Observable
{
  public void addObserver(Observer observer);
  public void removeObserver(Observer observer);
  public void notifyObservers();
}

Any class that wants to be observed must implement the Observable interface. Notice the three key methods:

  • Two methods for adding and removing observers
  • A method for updating observers

Normally, the addObserver() and removeObserver() methods are called by objects that wish to become observers. This is a useful abstraction because it avoids the need for this logic to be added to the observable class. In other words, the decision to add or remove observers is made outside of the observerGui object.

Listing 3 illustrates the mechanism.

Listing 3 Creating the observable and the observers

ObserverGui observerGui = new ObserverGui();
observerGui.setVisible(true);
ObserverEntity anObserver = new ObserverEntity();
ObserverEntity anotherObserver = new ObserverEntity();
observerGui.addObserver(anObserver);
observerGui.addObserver(anotherObserver);

Listing 3 is in fact the main() method of the program. Let’s have a look at it.

To begin with, an object observerGui of the class ObserverGui is instantiated. This object is the observable entity, and the third and fourth lines in Listing 3 create the ObserverEntity objects (the observers). The program logic then adds the two ObserverEntity objects to the list of subscribers. Any changes that are made to the observed data will now be propagated to the objects of the ObserverEntity class.

Let’s now have a closer look at the observer classes.

  • + Share This
  • 🔖 Save To Your Account