The ObserverEntity Class
An instance of the ObserverGui class (such as observerGui) can be seen as the data server and the observers must subscribe in order to receive notification of data changes.
This means that the clients of the observerGui object must implement the Observer interface. This allows for data changes to be communicated to the subscribers. For this purpose, we have Listing 4, which illustrates the class ObserverEntity.
Listing 4 ObserverEntity class
public class ObserverEntity implements Observer { ObserverEntity() { } public void addObserver(Observer observer) { } public void removeObserver(Observer observer) { } public void notifyObservers(String newKeyData) { System.out.println("Data change occurred - new data is " + newKeyData); } }
Objects of the ObserverEntity class are instantiated in Listing 3, and these instances are in turn added to the list of observers of the observerGui object.
So, how do data changes in the observerGui object get communicated to the observers? Just click the Update Key Data button (refer to Figure 1), and the following code (in Listing 5) is executed.
Listing 5 A change occurs to the observed data
public void actionPerformed(ActionEvent e) { String actionCommand = e.getActionCommand(); if (actionCommand.equals("Update Key Data")) { // Make a change to the observed data keyData+= "22"; message.setText("Updating all observers - new key data " + keyData); // Notify all observers notifyObservers(); } else if (actionCommand.equals("Exit")) { message.setText("Exit"); dispose(); } else { message.setText("Unexpected Error."); } }
The main action in Listing 5 takes place in the first if statement. The data change that occurs is to append the string "22" to the data item.
Next, this change is reflected in the GUI, as illustrated in Figure 2.
Figure 2 A data change occurs!
So, we can see the data has changed in the GUI.
The last thing to happen is the observer update, which occurs when the following line of code executes:
notifyObservers();
This method call results in a call to the observer clients and the following text (in Listing 6) should appear on the console:
Listing 6 The disseminated data
Data change occurred - new data is Data Item 22 Data change occurred - new data is Data Item 22
Where does the program output in Listing 6 come from? It comes from the last line of Listing 4 and the reason why this output occurs twice in Listing 7 is because we have two observer objects.
You can easily confirm that we have two observers by looking at Listing 3, in which two instances of ObserverEntity are created and added to the observerGui object.