Home > Articles > Programming > Java

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

The Publish-and-Subscribe Model

Figure 1 illustrates the GUI for the Java program I’ll be using.

Figure 1

Figure 1 The observer pattern in action

In Figure 1, an object (called observerGui) of a Java class called ObserverGui owns the GUI. We can think of the object observerGui as the owner of the data that will in turn be used by the observers.

So, Figure 1 represents our data source. Other objects then subscribe in order to learn about changes to the data.

In Figure 1, the Update Key Data button is used to cause a change to the observed data item. Once this button is pressed, the key data changes, and we need to disseminate this change to any listening objects. We’ll see this mechanism in action a little later on.

Listing 1 illustrates the data source that is maintained by the object.

Listing 1 The data source

private String keyData = "Data Item ";
private ArrayList observers = new ArrayList();

Nothing too amazing there! The object observerGui owns a private String data member called keyData and a private ArrayList of observer objects. Another term that can be applied to the object observerGui is observable. This simply means that because objects can subscribe to observerGui, the latter is said to be observable. In some sense, an observable entity is a type of server.

Let’s now have a look at the observers.

  • + Share This
  • 🔖 Save To Your Account