
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
384
|
Chapter 17: The Singleton Design Pattern
Let’s compare the Logger class with the generic Singleton implementation from
Example 17-1. The Logger’s
log property stores the single Logger instance and is
equivalent to Example 17-1’s
_instance property. As in Example 17-1, the Logger
class constructor is private, but this time the constructor actually performs a useful
action (setting the log level). Finally, the Logger.getLog( ) method provides access to
the Logger instance in
log, exactly as getInstance( ) does in Example 17-1.
To send a testing debug message to the log, we use:
import logger.Logger;
var log:Logger = Logger.getLog( );
log.debug("Testing...testing...");
Or, more succinctly:
import logger.Logger;
Logger.getLog( ).debug("Testing...testing...");
No matter where the preceding code appears in our application, the log message is
guaranteed to be routed through the same, lone Logger instance. Hence, we can be
sure that all log messages in the application are processed in the same way (i.e., are
handled by the same Logger observers).
Singleton Versus Class Methods
and Class Properties
You might wonder why we wouldn’t implement the Logger class’s functionality
entirely in class methods and class properties. That is, why not design Logger to be
used directly through class methods instead ...