单例模式
作用:
保证一个类只有一个实例来提供全局的访问点。可以避免对象的频繁创建和销毁,减少内存、资源开销。
类图:
- 角色划分:
- 图示:
代码:
class Singleton {
// 唯一实例
private static $_instance = null;
public function __construct() {
echo "单例模式的实例被构造了";
echo PHP_EOL;
}
public static function getInstance() {
if (!(self::$_instance instanceof Singleton)) {
self::$_instance = new Singleton();
}
return self::$_instance;
}
// 防止克隆
public function __clone() {}
}
// 测试
$test1 = Singleton::getInstance();
$test2 = Singleton::getInstance();
print_r($test1 === $test2);
实例:
<?php
/*
* mysql 单例
*/
class mysql{
private $host ='localhost'; //数据库主机
private $user