Home >Backend Development >PHP Tutorial >PHP 设计模式系列 -- 注册模式(Registry)

PHP 设计模式系列 -- 注册模式(Registry)

WBOY
WBOYOriginal
2016-06-23 13:20:151291browse

1、模式定义

注册模式 (Registry)也叫做注册树模式,注册器模式。注册模式为应用中经常使用的对象创建一个中央存储器来存放这些对象 —— 通常通过一个只包含静态方法的抽象类来实现(或者通过单例模式)。

2、UML类图

3、示例代码

Registry.php

<?phpnamespace DesignPatterns\Structural\Registry;/** * class Registry */abstract class Registry{    const LOGGER = 'logger';    /**     * @var array     */    protected static $storedValues = array();    /**     * sets a value     *     * @param string $key     * @param mixed  $value     *     * @static     * @return void     */    public static function set($key, $value)    {        self::$storedValues[$key] = $value;    }    /**     * gets a value from the registry     *     * @param string $key     *     * @static     * @return mixed     */    public static function get($key)    {        return self::$storedValues[$key];    }    // typically there would be methods to check if a key has already been registered and so on ...}

4、测试代码

Tests/RegistryTest.php

<?phpnamespace DesignPatterns\Structural\Registry\Tests;use DesignPatterns\Structural\Registry\Registry;class RegistryTest extends \PHPUnit_Framework_TestCase{    public function testSetAndGetLogger()    {        Registry::set(Registry::LOGGER, new \StdClass());        $logger = Registry::get(Registry::LOGGER);        $this->assertInstanceOf('StdClass', $logger);    }}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:多玩某GM系统敏感信息泄漏Next article:php操作mysql