注册树模式可以集中管理对象,方便调用。下面让单例模式跟注册树模式来个小小的结合
代码:
// final禁止继承
final class Singleton
{
// 保存实例
private static $instance;
// 防止类在外部被实例化
private function __construct()
{
}
// 防止对象被复制
private function __clone()
{
}
// 单例入口
public static function getInstance()
{
if( !(self::$instance instanceof self) ) {
self::$instance = new self();
// echo "new"; // 测试代码
}
// echo "get\n"; // 测试代码
return self::$instance;
}
// 测试方法
public function test()
{
echo 'test';
}
}
// 注册树
class Register
{
// 注册树
protected static $tree = array();
// 挂上注册树
public static function set($key, $value) {
self::$tree[$key] = $value;
}
// 获取注册树内容,没有内容返回空
public static function get($key) {
return isset(self::$tree[$key]) ? self::$tree[$key] : null;
}
// 移除注册树内容,final禁止覆盖,存在$key则删除
final public static function remove($key) {
if ( array_key_exists($key, self::$tree) ) {
unset(self::$tree[$key]);
}
}
}
// 使用方法
// 获取
$singleton = Register::get('singleton');
echo "1:";
print_r($singleton);
// 设置
Register::set('singleton', Singleton::getInstance());
$singleton = Register::get('singleton');
echo "\n2:";
print_r($singleton);
$singleton->test();
// 删除
Register::remove('singleton');
$singleton = Register::get('singleton');
echo "\n3:";
print_r($singleton);