PHP设计模式 -注册模式

2019-04-22 19:49 By 茹茹 2830 0 0

【一】模式定义

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


【二】UML类图

image.png


【三】示例代码

Registry.php

<?php

namespace 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 ...
}


【四】测试代码

Tests/RegistryTest.php

<?php

namespace 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);
    }
}


注:本文转载自 Laravel学院 ,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责。
如有侵权行为,请联系我们,我们会及时删除。

评 论

View in WeChat

Others Discussion

  • 2018年云计算热词
    Posted on 2019-06-12 18:19
  • PHP 基金会来啦!
    Posted on 2022-10-08 17:40
  • 快速了解Kafka
    Posted on 2021-03-25 14:20
  • Redis各种数据类型的使用场景举例分析【二】
    Posted on 2018-11-22 10:30
  • TCP协议的特性
    Posted on 2019-04-26 16:46
  • 让你的PHP7更快(GCC PGO)
    Posted on 2018-03-07 14:09
  • Composer 异常 [ErrorException]
    Posted on 2019-11-25 17:55
  • BASE原则
    Posted on 2020-12-17 16:42