工厂模式为了减少不断的new操作,单例模式为了维持全局唯一的实例,注册树模式跟这两种模式类似的地方在于减少并维持某个实例、变量的唯一性,而不同的地方在于注册树模式将这些实例、变量等放到全局(或相对全局)来进行统一管理调度,而不像工厂与单例模式那么闲散。
注册树模式,顾名思义,该模式实现将某个东西注册(挂)到某棵树的方法。随即引出实现该模式的几个要点:
1.有棵树;
2.注册(挂)到树的方法;
3.读取的方法(实现用的功能,不能干挂着不做事);
4.注销的方法(有注册就要有注销的功能)
实现如下:
class Register {
// 一棵大树
protected static
t
r
e
e
=
[
]
;
/
/
挂
到
树
上
p
u
b
l
i
c
s
t
a
t
i
c
f
u
n
c
t
i
o
n
s
e
t
(
tree = []; // 挂到树上 public static function set(
tree=[];//挂到树上publicstaticfunctionset(key, KaTeX parse error: Expected '}', got 'EOF' at end of input: … self::tree[$key] = KaTeX parse error: Expected 'EOF', got '}' at position 12: value; }̲ // 读取树上的节点…key)
{
return isset(self::
t
r
e
e
[
tree[
tree[key]) ? self::
t
r
e
e
[
tree[
tree[key] : null;
}
// 取下树的节点
public static function _unset(KaTeX parse error: Expected '}', got 'EOF' at end of input: … unset(self::tree[$key]);
}
}
使用方式:
// 将某个东西挂到树上
Register::set(‘db’, ‘db_value’)
// 读取
Register::get(‘db’);
// 注销
Register::_unset(‘db’);
通常,在项目初始化或载入某些模块的时候进行树的注册。