Register Tree mode (Registry pattern): The registration tree mode creates a central memory for objects that are used frequently in the application-usually through an abstract class that contains only static methods (or through singleton mode). Also known as the Registrar mode
(a) Why registration of tree mode is required
解决常用对象的存放问题,实现类似于全局变量的功能。
(ii) registration tree mode UML diagram
Not currently
(c) Simple examples
<?phpThe user class is used for testingClassuser{}Registering Tree ClassesClassregistry{ProtectedStatic $objects;For storing instancesDeposit instance MethodStaticPublicfunctionSet($key, $object) {Self:: $objects [$key] = $object; }Get instance methodStaticPublicfunctionGet($key) {if (!IssetSelf:: $objects [$key]) {ReturnFALSE;} return self:: $objects [$key];} //Delete instance method static public function _unset ($key) {unset (self:: $objects [$ Key]); }} $user = new user; Deposit Instance Registry::set ( ' User ', $user); Delete Instance Registry::_unset ( "User");
The registration tree is often used in conjunction with Singleton mode, first to see if there is an instance on the registration tree, to use it directly, to generate an instance, and to hang it on the tree. Sometimes we can also do this, let get method if get not to the instance of the time when the new one is stored, so that we use no tube has stored this instance, anyway, the Get method will also help us to store.
//获取实例方法 static public function get($key) { if (!isset(self::$objects[$key])) { self::$objects[$key] = new $key; } return self::$objects[$key]; }
Of course, if you use this method, you can't use the Get method if you see if the instance exists. An instance is generated because the Get method is called after it does not exist.
PHP implements the registration tree mode