本文實例講述了PHP設計模式之工廠模式與單例模式實現方法。分享給大家供大家參考,具體如下:
設計模式簡單說應對某類問題而設計的解決方式
工廠模式:應對需求創建相應的對象
1
2
3
4
5
6
7
8
9
|
class factory{ function __construct( $name ){ if ( file_exists ( './' . $name . '.class.php' )){ return new $name ; } else { die ( 'not exist' ); } } } |
單例模式:只創建一個對象的實例,不允許再創建實例,節約資源(例如數據庫的連接)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
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 ); |
運行結果如下:
1
2
3
4
5
|
20 object(instance)[1] public 'val' => int 20 object(instance)[1] public 'val' => int 20 |
應用:數據庫連接類(database access oject)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
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程序設計有所幫助。