PHP设计模式 -注册模式

2019-04-22 19:49 By 茹茹 2758 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

  • 一些常见的基础概念
    Posted on 2018-11-28 19:10
  • HTTP头中隐藏PHP版本号
    Posted on 2021-01-11 16:38
  • MySQL中的行级锁,表级锁,页级锁
    Posted on 2018-08-25 11:00
  • QPS、TPS、RT、吞吐量到底是什么
    Posted on 2020-02-02 01:15
  • MySQL事务介绍
    Posted on 2019-06-05 18:14
  • 能创建多少个 TCP 连接?
    Posted on 2021-08-02 16:00
  • PHP 基金会来啦!
    Posted on 2022-10-08 17:40
  • 2018年云计算热词
    Posted on 2019-06-12 18:19