Review PHP设计模式之——注册模式
注册模式:
1 class DbConnections{ 2 var $_store = array(); 3 public function isValid($key) { 4 return isset($this->_store[$key]); 5 } 6 7 public function &get($key){ 8 if (isset($this->_store[$key])) 9 return $this->_store[$key]; 10 } 11 12 public function set($key, & $obj) { 13 $this->_store[$key] = & $obj; 14 } 15 16 public function &getInstance(){ 17 static $instance = array(); 18 if (!$instance) 19 $instance[0] = & new DbConnections; 20 return $instance[0]; 21 } 22 } 23 24 class MysqlConnection{ 25 public $name = false; 26 public function __construct($db){ 27 $this->name = $db; 28 echo $db, "\n"; 29 } 30 31 public function append($str){ 32 $this->name .= " ".$str; 33 } 34 } 35 36 //initial setup, somewhere near the start of your script 37 $dbc = & DbConnections::getInstance(); 38 $dbc->set('server1', new MysqlConnection('db1')); 39 $dbc->set('server2', new MysqlConnection('db2')); 40 $dbc->set('server3', new MysqlConnection('db3')); 41 42 43 $dbc1 = $dbc->get('server1'); 44 $dbc2 = $dbc->get('server2'); 45 $dbc3 = $dbc->get('server3'); 46 47 $dbc1->append("connection"); 48 49 var_dump($dbc->get('server1')); 50 var_dump($dbc->get('server2')); 51 var_dump($dbc->get('server3'));