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'));
阅读全文
0 0
- php模式设计之 注册树模式
- 《PHP设计模式》之 注册树模式
- PHP设计模式之-----注册树模式
- php模式设计之 注册树模式
- PHP设计模式之注册模式
- 设计模式之注册器模式(PHP实现)
- PHP常见的设计模式之:注册树模式
- PHP之注册树模式
- 设计模式--注册模式
- php核心学习-设计模式的学习-注册树模式
- PHP设计模式-注册台模式(Registry)
- php 设计模式之 代理模式,适配器模式,外观模式
- PHP设计模式中之装饰模式
- PHP设计模式之Factory模式
- PHP设计模式之AbstractFactory模式
- PHP设计模式之Builder模式
- PHP设计模式之Prototype模式
- PHP设计模式之Singleton模式
- [nginx] fastcgi_cache 完整示例
- 简单工厂模式
- zoj 3870
- 父元素与子元素之间的margin-top问题
- PL/SQL Developer使用技巧(转)
- PHP设计模式之注册模式
- JavaScript(三)闭包
- 【设计模式】-工厂模式
- Python核心数据类型及类型显示转换
- 03:计算矩阵边缘元素之和
- Java学习笔记(16)--方法重载篇
- c++动态内存管理
- SAP MM PA考试模拟试题
- 杭电oj2104题hide handkerchief