Singleton Pattern (Nhóm khởi tạo)
Đảm bảo một class chỉ có MỘT instance duy nhất, và nó trở thành instance toàn cục cho toàn bộ lifecycle của ứng dụng. Hữu ích khi cần một đối tượng duy nhất để điều phối các hành động trong hệ thống.
🔍 Dấu hiệu nhận biết
Cần tái sử dụng trạng thái của đối tượng trong ứng dụng: mở Database Connection, tạo HTTP Client… - không muốn khởi tạo lại instance mới từ đầu, mà dùng instance đã có.
Ví dụ: Database Connection
<?php
class Database {
// Thuộc tính static lưu thể hiện duy nhất của lớp
private static $instance = null;
private $connection;
private $host = 'localhost';
private $username = 'root';
private $password = '';
private $database = 'example_db';
// Constructor PRIVATE: ngăn khởi tạo đối tượng từ bên ngoài
private function __construct() {
$this->connection = new mysqli($this->host, $this->username,
$this->password, $this->database);
if ($this->connection->connect_error) {
die("Connection failed: " . $this->connection->connect_error);
}
}
// static getInstance: đảm bảo chỉ khởi tạo duy nhất một instance
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new Database();
}
return self::$instance;
}
public function getConnection() { return $this->connection; }
}
$conn1 = Database::getInstance()->getConnection();
$conn2 = Database::getInstance()->getConnection();
if ($conn1 === $conn2) {
echo "Both connections are the same.\n"; // ← cùng MỘT instance
}Hai thành phần chính: constructor private (chặn new từ bên ngoài) + static getInstance() (điểm truy cập toàn cục, lazy-init).
Liên quan
- Factory Pattern, Builder Pattern - cùng nhóm khởi tạo
- Inversion of Control - Service Container thường quản lý singleton thay bạn