< Day Day Up > |
In Chapter 16, we created an application log using the Observer pattern. That application required a single, central logging facility, which we implemented in the Logger class. Now let's return to the Logger class and look at the specific code in it that implements the Singleton pattern. By using Singleton, the Logger class guarantees that the application using it creates only a single log, even if there are multiple observers displaying the log output in various ways. Example 17-2 shows the relevant section of the Logger class, omitting code that is not directly part of the Singleton pattern. (For the full Logger class listing, see Example 16-6 in Chapter 16.) Example 17-2. The Singleton pattern in the Logger classclass logger.Logger extends Observable { private static var log:Logger = null; private function Logger ( ) { setLevel(Logger.INFO); } public static function getLog( ):Logger { if (log == null) { log = new Logger( ); } return log; } } 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-1s _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). |
< Day Day Up > |