


Use registration tree and factory pattern instead of singleton pattern practice (with case)
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]); } } }
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; } }
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);
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

The JS singleton pattern is a commonly used design pattern that ensures that a class has only one instance. This mode is mainly used to manage global variables to avoid naming conflicts and repeated loading. It can also reduce memory usage and improve code maintainability and scalability.

The benefits of the Java factory pattern: 1. Reduce system coupling; 2. Improve code reusability; 3. Hide the object creation process; 4. Simplify the object creation process; 5. Support dependency injection; 6. Provide better performance; 7. Enhance testability; 8. Support internationalization; 9. Promote the open and closed principle; 10. Provide better scalability. Detailed introduction: 1. Reduce the coupling of the system. The factory pattern reduces the coupling of the system by centralizing the object creation process into a factory class; 2. Improve the reusability of code, etc.

The factory pattern is used to decouple the creation process of objects and encapsulate them in factory classes to decouple them from concrete classes. In the Java framework, the factory pattern is used to: Create complex objects (such as beans in Spring) Provide object isolation, enhance testability and maintainability Support extensions, increase support for new object types by adding new factory classes

Detailed explanation of Java Factory Pattern: Understand the differences and application scenarios of simple factories, factory methods and abstract factories Introduction In the software development process, when faced with complex object creation and initialization processes, we often need to use the factory pattern to solve this problem. As a commonly used object-oriented programming language, Java provides a variety of factory pattern implementations. This article will introduce in detail the three common implementation methods of the Java factory pattern: simple factory, factory method and abstract factory, and conduct an in-depth analysis of their differences and application scenarios. one,

Factory Pattern In Go, the factory pattern allows the creation of objects without specifying a concrete class: define an interface (such as Shape) that represents the object. Create concrete types (such as Circle and Rectangle) that implement this interface. Create a factory class to create objects of a given type (such as ShapeFactory). Use factory classes to create objects in client code. This design pattern increases the flexibility of the code without directly coupling to concrete types.

Singleton pattern: Provide singleton instances with different parameters through function overloading. Factory pattern: Create different types of objects through function rewriting to decouple the creation process from specific product classes.

In software development, we often encounter situations where multiple objects need to access the same resource. In order to avoid resource conflicts and improve program efficiency, we can use design patterns. Among them, the singleton pattern is a commonly used way to create objects, which ensures that a class has only one instance and provides global access. This article will introduce how to use PHP to implement the singleton pattern and provide some best practice suggestions. 1. What is the singleton mode? The singleton mode is a commonly used way to create objects. Its characteristic is to ensure that a class has only one instance and provides

Thinking about thread safety issues of singleton mode in PHP In PHP programming, singleton mode is a commonly used design pattern. It can ensure that a class has only one instance and provide a global access point to access this instance. However, when using the singleton pattern in a multi-threaded environment, thread safety issues need to be considered. The most basic implementation of the singleton pattern includes a private constructor, a private static variable, and a public static method. The specific code is as follows: classSingleton{pr
