单例模式保证了一个类中只有一个实例被全局访问,当你有一组全局对象被全局访问时可能就需要用到注册者模式 (registry),它提供了在程序中有条理的存放并管理对象 (object)一种解决方案。一个“注册模式”应该提供get() 和 set()方法来存储和取得对象(用一些属性key)而且也应该提供一个isValid()方法来确定一个给定的属性是否已经设置。 注册模式通过单一的全局的对象来获取对其它对象的引用
实例 1:
//注册模式 class Registry { protected static $store = array(); private static $instance; public static function instance() { if(!isset(self::$instance)) { self::$instance = new self(); } return self::$instance; } public function isValid($key) { return array_key_exists($key,Registry::$store); } public function get($key) { if (array_key_exists($key,Registry::$store)) return Registry::$store[$key]; } public function set($key, $obj) { Registry::$store[$key] = $obj; } } //数据库链接类 class ConnectDB { private $host; private $username; private $password; private $conn; public function __construct($host, $username, $password){ $this->host = $host; $this->username = $username; $this->password = $password; } public function getConnect() { return mysql_connect($this->host,$this->username,$this->password); } } //使用测试 $reg = Registry::instance(); $reg->set('db1', new ConnectDB('localhost', 'root', '123456')); $reg->set('db2', new ConnectDB('192.168.1.198', 'test', '0K5Dt@2jdc8#x@')); print_r("<pre>"); print_r($reg->get('db1')); print_r($reg->get('db2'));
注册模式,解决全局共享和交换对象。已经创建好的对象,挂在到某个全局可以使用的数组上,在需要使用的时候,直接从该数组上获取即可。将对象注册到全局的树上。任何地方直接去访问。
实例2:
class Register { //定义全局属性 protected static $objects; //将对象注册到全局的树上 function set($alias,$object) { //将对象放到树上 self::$objects[$alias]=$object; } static function get($name){ //获取某个注册到树上的对象 return self::$objects[$name]; } function _unset($alias) { //移除某个注册到树上的对象。 unset(self::$objects[$alias]); } }