CHAPTER 4 – Singleton Pattern

4.4.2 Singleton Pattern The singleton pattern is probably one of the best-known design patterns. You have probably encountered many situations where you have an object that handles some centralized operation in your application, such as a logger object. In such cases, it is usually preferred for only one such application-wide instance to exist and for all application code to have the ability to access it. Specifically, in a logger object, you would want every place in the application that wants to print something to the log to have access to it, and let the cen- tralized logging mechanism handle the filtering of log messages according to log level settings. For this kind of situation, the singleton pattern exists. Making your class a singleton class is usually done by implementing a static class method getInstance(), which returns the only single instance of the class. The first time you call this method, it creates an instance, saves it in a private static variable, and returns you the instance. The subsequent times, it just returns you a handle to the already created instance. Here's an example: class Logger { static function getInstance() { if (self::$instance == NULL) { self::$instance = new Logger(); } return self::$instance; } private function __construct() { } private function __clone() {

} function Log($str) { // Take care of logging } static private $instance = NULL; } Logger::getInstance()->Log("Checkpoint"); PHP 5 Advanced OOP and Design Patterns Chap. 4 The essence of this pattern is Logger::getInstance(), which gives you access to the logging object from anywhere in your application, whether it is from a function, a method, or the global scope. In this example, the constructor and clone methods are defined as pri- vate. This is done so that a developer can't mistakenly create a second instance of the Logger class using the new or clone operators; therefore, getIn- stance() is the only way to access the singleton class instance.

Post Comment
Login to post comments