在PHP中,单例模式(Singleton Pattern)是一种常用的设计模式,用于确保一个类只有一个实例,并提供一个全局访问点。单例模式适用于以下场景:
解决方案:使用单例模式确保只有一个数据库连接实例,避免资源浪费。
class Database {
private static $instance = null;
private $connection;
private function __construct() {
$this->connection = new PDO("mysql:host=localhost;dbname=test", "user", "password");
}
public static function getInstance() {
if (self::$instance == null) {
self::$instance = new Database();
}
return self::$instance;
}
public function getConnection() {
return $this->connection;
}
}
$db = Database::getInstance();
$conn = $db->getConnection();
解决方案:使用单例模式确保配置信息只加载一次,避免重复读取配置文件。
class Config {
private static $instance = null;
private $config = [];
private function __construct() {
$this->config = parse_ini_file('config.ini');
}
public static function getInstance() {
if (self::$instance == null) {
self::$instance = new Config();
}
return self::$instance;
}
public function get($key) {
return $this->config[$key] ?? null;
}
}
$config = Config::getInstance();
$dbHost = $config->get('db_host');
解决方案:使用单例模式确保日志记录器只有一个实例。
class Logger {
private static $instance = null;
private $logFile;
private function __construct() {
$this->logFile = fopen('app.log', 'a');
}
public static function getInstance() {
if (self::$instance == null) {
self::$instance = new Logger();
}
return self::$instance;
}
public function log($message) {
fwrite($this->logFile, $message . PHP_EOL);
}
public function __destruct() {
fclose($this->logFile);
}
}
$logger = Logger::getInstance();
$logger->log('This is a log message.');
解决方案:使用单例模式确保缓存系统只有一个实例。
class Cache {
private static $instance = null;
private $cache = [];
private function __construct() {}
public static function getInstance() {
if (self::$instance == null) {
self::$instance = new Cache();
}
return self::$instance;
}
public function set($key, $value) {
$this->cache[$key] = $value;
}
public function get($key) {
return $this->cache[$key] ?? null;
}
}
$cache = Cache::getInstance();
$cache->set('foo', 'bar');
echo $cache->get('foo'); // 输出: bar
解决方案:使用单例模式确保服务定位器只有一个实例。
class ServiceLocator {
private static $instance = null;
private $services = [];
private function __construct() {}
public static function getInstance() {
if (self::$instance == null) {
self::$instance = new ServiceLocator();
}
return self::$instance;
}
public function register($name, $service) {
$this->services[$name] = $service;
}
public function get($name) {
return $this->services[$name] ?? null;
}
}
$locator = ServiceLocator::getInstance();
$locator->register('db', new PDO("mysql:host=localhost;dbname=test", "user", "password"));
$db = $locator->get('db');
解决方案:使用单例模式确保线程池只有一个实例。
class ThreadPool {
private static $instance = null;
private $pool = [];
private function __construct() {}
public static function getInstance() {
if (self::$instance == null) {
self::$instance = new ThreadPool();
}
return self::$instance;
}
public function addThread($thread) {
$this->pool[] = $thread;
}
public function getThreads() {
return $this->pool;
}
}
$pool = ThreadPool::getInstance();
$pool->addThread(new Thread());
解决方案:使用单例模式确保全局状态只有一个实例。
class GlobalState {
private static $instance = null;
private $state = [];
private function __construct() {}
public static function getInstance() {
if (self::$instance == null) {
self::$instance = new GlobalState();
}
return self::$instance;
}
public function set($key, $value) {
$this->state[$key] = $value;
}
public function get($key) {
return $this->state[$key] ?? null;
}
}
$state = GlobalState::getInstance();
$state->set('user', 'John Doe');
echo $state->get('user'); // 输出: John Doe
单例模式在PHP中的应用场景非常广泛,尤其是在需要全局唯一实例的情况下。通过单例模式,可以有效地管理资源、配置、日志、缓存等,确保应用程序的高效运行和资源的合理利用。