PHP设计模式之注册模式

来源:互联网 发布:mac系统解压缩软件 编辑:程序博客网 时间:2024/06/06 03:05
单例模式保证了一个类中只有一个实例被全局访问,当你有一组全局对象被全局访问时可能就需要用到注册者模式 (registry),它 提供了在程序中有条理的存放并管理对象 (object)一种解决方案。一个“注册模式”应该提供get() 和 set()方法来存储和取得对象(用一些属性key)而且也应该提供一个isValid()方法来确定一个给定的属 性是否已经设置。 注册模式通过单一的全局的对象来获取对其它对象的引用 实例:
    <?php      /**      * PHP设计模式之注册模式实例      *       * @link  <a href="http://www.phpddt.com" target="_blank">http://www.phpddt.com</a>  */      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', 'mckee'));      $reg->set('db2', new ConnectDB('192.168.1.198', 'test', '0K5Dt@2jdc8#x@'));      print_r($reg->get('db1'));      print_r($reg->get('db2'));