php设计模式入门-注册表模式

来源:互联网 发布:java创建文件夹和文件 编辑:程序博客网 时间:2024/05/18 01:39

对于这个模式的应用场景不是太好总结,只是根据之前的经验,注册表类里面经常会存储一些别的地方需要用到的对象,比如redis、memcache类,还比如配置信息config类等,它扮演的是一个类似于全局变量的角色。具体的实现其实非常简单,如下代码所示:

<?phpclass Registry{     static $instance;     public $containers = array();     static function getInstance(){          if(is_null(self::$instance)){               self::$instance = new self();          }          return self::$instance;     }     public function set($key, $value){          $this->containers[$key] = $value;     }     public function get($key){          return isset($this->containers[$key]) ? $this->containers[$key] : null;     }}$registry = Registry::getInstance();$registry->set('key1', 'hello');<span style="white-space:pre"></span>//只是为了测试,通常注册表中存储的数据都是对象var_dump($registry->get('key1'));var_dump($registry->get('key2'));


0 0
原创粉丝点击