Singleton
8/8/25Less than 1 minute
Description
Singleton is a creational design pattern, which ensures that only one object of its kind exists and provides a single point of access to it for any other code.
- Singleton là 1 creational design pattern.
- Giúp chắc chắn chỉ có duy nhất 1 object được tạo và truy xuất ở bất kì đâu. Eg: Kết nối DB, Notification,..-> Có thể dùng global variable nhưng sẽ phá vỡ tính đóng gói (encapsulation) của OOP.
Mục đích sử dụng:
- Sử dụng với các object cần share resource: Logger, Configuration, Cache
- Triển khai 1 số pattern khác: Abstract Factory, Builder, Prototype, Facade,..
Example
Logger
?php
class Singleton
{
private static $_instances = [];
protected function __construct()
{
}
public function __wakeup()
{
throw new \Exception("Cannot unserialize singleton");
}
public static function getInstance()
{
$subClass = static::class;
if (!isset(self::$_instances[$subClass])) {
self::$_instances[$subClass] = new static();
}
return self::$_instances[$subClass];
}
}
class Logger extends Singleton
{
public $driver;
public function setDriver($driver)
{
$this->driver = $driver;
}
public function getDriver()
{
return $this->driver;
}
}
$logger1 = Logger::getInstance();
$logger1->setDriver('file');
$logger2 = Logger::getInstance();
echo $logger2->getDriver();
refer: https://refactoring.guru/design-patterns/singleton/php/example