php 注册器模式 工厂模式

<?php
/**
 * 注册器模式
 * 全局共享和交换对象
 */

class Register
{
    public static $objects; // 定义全局数组

    // 保存对象到全局数组
    public static function set($name,$object)
    {
        self::$objects[$name] = $object;
    }

    // 获取某个对象
    public static function get($name)
    {
        if (!isset(self::$objects[$name])){
            return false;
        }
        return self::$objects[$name];
    }

    // 获取全部对象
    public static function getAll()
    {
        return self::$objects;
    }

    // 删除指定对象
    public function remove($name)
    {
        unset(self::$objects[$name]);
    }
}

class Db
{
    public function say()
    {
        echo 444444444444;
    }
}


class Factory
{
    public static function getDb()
    {
        $db = new Db();
        Register::set(‘db‘,$db);
        return $db;
    }
}

Factory::getDb();
$db = Register::get(‘db‘);
var_dump($db->say());

https://zhuanlan.zhihu.com/p/110541976

https://cloud.tencent.com/developer/article/1556340

https://www.cnblogs.com/rxbook/p/10452582.html

相关推荐