PHP Design Patterns _ registered tree pattern

Can be easier and faster access to the object model by registering tree, somewhere instantiate an object, you can "save up" (in an array can be used globally in) the object, use only when needed to save the object when that identification can solve the global sharing and exchange objects, directly from the array can be.

Why use a registered tree pattern?

Singleton pattern to solve is how to create a unique instance of an object in the entire project problems, the factory model to address is how the method does not create an instance of an object by new. The registrar tree pattern trying to solve the problem? Before considering this question, we need to consider the limitations under the first two models currently facing. First, the process creates a unique mode of embodiment of the object itself, there is a single determination, i.e., determines whether the object exists. Return the object exists, it does not exist, create an object and returns. Each time you create an instance object must exist so one judge. Factory mode more consideration is extended maintenance issues. In general, singleton and factory mode produces a more reasonable target. How easy call these objects? And objects within a project such as the establishment of stragglers like, inconvenient overall management arrangements ah. Thus, registration tree pattern emerged. Whether you are by singleton or factory patterns or objects generated by a combination of both, are all to me "into the" registration tree.

	//单例模式
	class DataBase{
		private static $ins;
		public static function getInstance(){
			if(self::$ins instanceof self){
				return self::$ins;
			}
			self::$ins = new self();
			return self::$ins;
		}
	}
	//工厂模式
	class Factory{
		public static function createDb(){
			$db = DataBase::getInstance();
			Register::set("testdb",$db);
			return $db;
		}
	}
	//注册树模式
	class Register{
		protected static $object;
		public static function set($name,$obj){
			self::$object[$name]=$obj;
		}
		public function get($name){
			$obj=null;
			if(isset(self::$object[$name])){
				$obj = self::$object[$name];
			}
			return $obj;
		}
	}
	$objFact = new Factory();
	$db = $objFact->createDb();

	$objreg = new Register();
	$objInfo = $objreg->get("testdb");
	var_dump($objInfo);

  

Guess you like

Origin www.cnblogs.com/zh718594493/p/12122071.html