
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
360
|
Chapter 16: The Observer Design Pattern
Logger: A Complete Observer Example
Now that we’ve implemented the core of the Observer pattern, let’s put it to use in a
real-world example—an application log. To create the log, we’ll define four classes:
Logger, LogMessage, OutputPanelView, and TextFieldView, all of which reside in the
logger package. The Logger class is our subject. The OutputPanelView and
TextFieldView classes are our observers. The LogMessage class is our info object.
Any class in the application can send a message to the Logger class. The receipt of a
new message constitutes a change in the Logger class’s state, causing it to broadcast
the change (i.e., the message) to all Logger observers. In our case, the Logger observ-
ers are OutputPanelView and TextFieldView. The OutputPanelView renders log mes-
sages to the Output panel in Flash’s Test Movie mode. The TextFieldView renders log
messages to a text field on the movie’s Stage, allowing them to be seen at runtime in
the Flash Player.
Our Logger class uses the push model to broadcast messages. When a message
arrives, Logger creates a LogMessage instance and passes that instance on to its list of
observers. Each LogMessage provides methods for retrieving the text and severity of
the message logged. LogMessage instances ...