本文實例講述了PHP設計模式之工廠模式與單例模式實現方法。分享給大家供大家參考,具體如下:
設計模式簡單說應對某類問題而設計的解決方式
工廠模式:應對需求創建相應的對象
class factory{ function __construct($name){ if(file_exists('./'.$name.'.class.php')){ return new $name; }else{ die('not exist'); } } }
單例模式:只創建一個對象的實例,不允許再創建實例,節約資源(例如數據庫的連接)
class instance{ public $val = 10; private static $instance ; private function __construct(){} private function __clone(){} //設置為靜態方法才可被類調用 public static function getInstance(){ /*if(!isset(self::$instance)){ self::$instance = new self; }*/ if(!isset(instance::$instance)){ instance::$instance = new self; } return instance::$instance; } } $obj_one = instance::getInstance(); $obj_one->val = 20; //clone可以調用__clone()克隆即new出一個新的的對象 //$obj_two = clone $obj_one; $obj_two = instance::getInstance(); echo $obj_two->val; echo '<p>'; var_dump($obj_one,$obj_two);
運行結果如下:
20 object(instance)[1] public 'val' => int 20 object(instance)[1] public 'val' => int 20
應用:數據庫連接類(database access oject)
class mysqldb{ private $arr = array( 'port' => 3306, 'host' => 'localhost', 'username' => 'root', 'passward' => 'root', 'dbname' => 'instance', 'charset' => 'utf8' ); private $link; static $instance; private function __clone(){} private function __construct(){ $this->link = mysql_connect($this->arr['host'],$this->arr['username'],$this->arr['passward']) or die(mysql_error()); mysql_select_db($this->arr['dbname']) or die('db error'); mysql_set_charset($this->arr['charset']); } static public function getInsance(){ if(!isset(mysqldb::$instance)){ mysqldb::$instance = new self; } return mysqldb::$instance; } public function query($sql){ if($res = mysql_query($sql)){ return $res; }return false; } //fetch one public function get_one($sql){ $res = $this->query($sql); if($result = mysql_fetch_row($res)){ return $result[0]; } } //fetch row public function get_row($sql){ $res = $this->query($sql); if($result = mysql_fetch_assoc($res)){ return $result; } return false; } //fetch all public function get_all($sql){ $res = $this->query($sql); $arr = array(); while($result = mysql_fetch_assoc($res)){ $arr[] = $result; } return $arr; } } $mysql = mysqldb::getInsance();
更多關於PHP相關內容感興趣的讀者可查看本站專題:《php面向對象程序設計入門教程》、《PHP基本語法入門教程》、《PHP運算與運算符用法總結》、《PHP網絡編程技巧總結》、《PHP數組(Array)操作技巧大全》、《php字符串(string)用法總結》、《php+mysql數據庫操作入門教程》及《php常見數據庫操作技巧匯總》
希望本文所述對大家PHP程序設計有所幫助。