On this page
1. Singleton
The Singleton pattern is a design pattern that ensures a class has only one instance and provides a global point of access to that instance. This is useful when exactly one object is needed to coordinate actions across the system.
Key Characteristics:
- Single Instance: Only one instance of the class is created, ensuring that all requests use the same instance.
- Global Access: Provides a global point of access to the instance.
How It Works:
- Private Constructor: The constructor is made private to prevent the creation of multiple instances from outside the class.
- Static Instance: A static variable holds the single instance of the class.
- Static Method: A public static method is provided to access the single instance. This method ensures that the instance is created only once and returns the same instance on subsequent calls.
Example in PHP:
class Singleton {
// Holds the single instance of the class
private static $instance;
// Private constructor to prevent direct instantiation
private function __construct() {
// Initialization code
}
// Public static method to get the single instance
public static function getInstance() {
// Check if the instance is already created
if (self::$instance === null) {
// Create the instance if it does not exist
self::$instance = new Singleton();
}
// Return the single instance
return self::$instance;
}
// Prevent cloning of the instance
private function __clone() {}
// Prevent unserializing of the instance
private function __wakeup() {}
}
// Usage
$instance1 = Singleton::getInstance();
$instance2 = Singleton::getInstance();
// Check if both instances are the same
var_dump($instance1 === $instance2); // Output: bool(true)
Explanation:
- Private Constructor: The
__construct()
method is private, so no external code can create a new instance directly. - Static Method: The
getInstance()
method checks if the instance exists. If not, it creates it. This ensures that only one instance is ever created. - Private
__clone()
and__wakeup()
Methods: These methods prevent cloning and unserializing of the instance, which could otherwise lead to multiple instances.
Benefits:
- Controlled Access: Ensures that there is a single point of access to the instance.
- Global Access: Provides a global point of access to the instance, making it accessible from anywhere in the application.
Use Cases:
- Configuration Management: Useful for managing configuration settings where only one set of settings is needed.
- Resource Management: Ensures a single instance of resource-intensive objects, such as database connections.
The Singleton pattern helps manage shared resources efficiently and ensures that there is a single point of control in your application.