
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Logger: A Complete Observer Example
|
371
Notice that the five message-sending methods in the Logger class—fatal( ), error( ),
warn( ), info( ), and debug( )—all contain nearly identical code. In this example, we’ll
accept that redundancy in order to repeatedly demonstrate the general structure of a
state-change method. However, in a real-world version of the Logger class, we’d
move the repeated code to a centralized method that checks the log level and noti-
fies observers when appropriate. We’d call our centralized method handleMessage( )
and have each of the message-sending methods use it to validate and broadcast mes-
sages, as shown next:
// The new handleMessage( ) method.
public function handleMessage(msg:String, msgSeverity:Number):Void {
public function warn(msg:String):Void {
// If the filter level is at least "WARN", broadcast
// the message to observers.
if (logLevel >= Logger.WARN) {
lastMsg = new LogMessage(msg, Logger.WARN);
setChanged( );
notifyObservers(lastMsg);
}
}
/**
* Sends a message to the log, with severity "INFO".
*/
public function info(msg:String):Void {
// If the filter level is at least "INFO", broadcast
// the message to observers.
if (logLevel >= Logger.INFO) {
lastMsg = new LogMessage(msg, Logger.INFO);
setChanged( );
notifyObservers(lastMsg);
}
} ...