Use registration tree and factory pattern instead of singleton pattern practice (with case)

齐天大圣
Release: 2023-04-09 12:22:01
Original
1922 people have browsed it

Today I will introduce to you the next structural design pattern on the PHP Chinese website - registration tree mode, alias register mode or registration mode, which is used to save instances of objects frequently used in programs. The registration tree mode registers object instances to a global object tree and picks them from the object tree when needed. But unlike picking in reality, the fruit picked from the target tree still exists on the target tree, and you can continue to pick it next time.

Implementation code

The registrar pattern is very easy to understand and implement. Generally, there will be an attribute used to store multiple object instances, as well as set and get methods. The set method is used to save the object instance in the attribute array, and the get method is used to get the desired object instance.

class Registry
{
    // 保存实例对象
    private static $objs = [];
    
    // get获取实例对象
    public static function get(string $alias) : Object
    {
        if (!isset(self::$objs[$alias])) {
            throw new \Exception($alias . 'not found');
        }
        
        return self::$objs[$alias];
    }
    
    // set将实例对象注册到属性$objs中
    public static function set (string $alias, Object $obj) : void
    {
        if (!isset(self::$objs[$alias])) {
            self::$objs[$alias] = $obj;
        }
    }
    
    // 注销实例
    public static function unset (string $alias) :void
    {
        if (isset(self::$objs[$alias])) {
            unset(self::$objs[$alias]);
        }
    }
}
Copy after login

Use registration tree mode and factory mode instead of singleton mode

We know that singleton is very useful and can avoid resources Waste etc. However, the singleton pattern has been considered a negative pattern, and it is considered difficult to test and maintain the singleton pattern. As for why the singleton pattern is considered an anti-pattern, I won’t go into details here. Interested friends can google it by themselves.

So, are there any other ways for us to ensure singletons without using singleton mode? Yes, we can use registration tree mode and factory mode to replace singleton mode. The following is the specific code:

class Registry
{
    // 保存实例对象
    private static $objs = [];
    
    // get获取实例对象
    public static function get(string $alias) 
    {
        if (!isset(self::$objs[$alias])) {
            return null;
        }
        return self::$objs[$alias];
    }
    
    // set将实例对象注册到属性$objs中
    public static function set (string $alias, Object $obj) : void
    {
        if (!isset(self::$objs[$alias])) {
            self::$objs[$alias] = $obj;
        }
    }
    
    // 注销实例
    public static function unset (string $alias) :void
    {
        if (isset(self::$objs[$alias])) {
            unset(self::$objs[$alias]);
        }
    }
}

class DbFactory
{
    const ALIAS = 'Db';
    
    public static function create ()
    {
        $db = Registry::get(self::ALIAS);
        if (!$db) {
            $db = new Db([
                'host' => 'localhost',
                'user' => 'root',
                'pass' => '',
                'db_name' => 'test'
            ]);
            Registry::set(self::ALIAS, $db);
        }
        
        return $db;
    }
}
Copy after login

When we need a Db instance, we only need to call DbFactory::create. This method guarantees a singleton. The following is the test code:

$db = DbFactory::create();
var_dump($db);
Copy after login

Related recommendations:

1.PHP Design Pattern Simple Factory Pattern

2. One article to understand the simple factory, factory method, abstract factory

3.One article to understand the proxy pattern of PHP design pattern

4.php design pattern: Bridge mode learning experience (with case code)

The above is the detailed content of Use registration tree and factory pattern instead of singleton pattern practice (with case). For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!