1.1 Factory mode, factory method or class generate object, not in code direct new
Class factory{ static function Getdatabase () { return new Mysql ($host, $user, $pass); } } #使用 factory::getdatabase ();
1.2 Singleton mode, which causes an object of a class to run only to create a
1. There is a private static object variable, specifically for the object of this class
2. There is a static method to create the object
3 a private constructor to prevent the external new object
4. There is a clone method to prevent clone return False
Reference Article Singleton mode
Class Database {//Single object property private static $instance; Define some global variables that need to hold the property private $props = Array (); Private Function __construct () {echo ' into construct! the class does not allow external creation of objects '; }//Returns a singleton public static function getinstance () {//To determine if an instantiated object already exists if (Empty (self:: $instance)) { Can be override (dynamic parsing) Self:: $instance = new static (); Cannot be override (static parsing)//self:: $instance = new self (); } return Self:: $instance; } public Function __clone () {return ' This class prohibits clone '; }//Set property public function SetProperty ($key, $value) {$this->props[$key] = $value; }//Get property Public Function Getpeoperty ($key) {return $this->props[$key]; }}//Use $DBOBJ = Database::getinstance (); $DBOBJ->setproperty (' Root_path ', '/www '); $DBOBJ->setproperty (' Tmp_path ', '/tmp '); Next delete the Singleton object, if you can also get the property you just added, it means that you are using the same object unset ($dbOBJ); $DBOBJ = Database::getinstance (); echo $dbObj->getpeoperty (' Root_path '); echo $dbObj->getpeoperty (' Tmp_path ');
1.3 Registration mode, global share and Swap objects
1. The same need to use the unified registration of the object multiple aliases, unified call to use, (such as customers buy a machine must go to the factory identified institutions to buy, not everyone to the factory to buy)
2. The next time you want to use an object, do not need to use the factory, nor need to use a singleton mode, directly on the registrar to get it
Class Register () { protected static $objects; function set ($alias, $object) {self :: $objects [$alias] = $objects; } function Get ($alias) { return self:: $objects [$alias]; } function _unset ($alias) { unset (self:: $objects [$alias]); } }
2. Summary use
Class factory{ static function Getdatabase () { //Singleton mode gets the data object $DBOBJ = Database::getinstance (); Register to the Global Tree register::set (' db1 ', $DBOBJ); } } #使用 //First main file inside factory::getdatabase (); Access the register::get (' db1 ') directly using the database object in the future;
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.