PHP璁捐妯″紡
璁捐妯″紡
浣跨敤璁捐妯″紡鏄績杩涙渶浣冲疄璺靛拰鑹ソ璁捐鐨勫ソ鍔炴硶銆傝璁℃ā寮忓彲浠ユ彁渚涢拡瀵瑰父瑙佺殑缂栫▼闂鐨勭伒娲荤殑瑙e喅鏂规銆
宸ュ巶妯″紡
宸ュ巶妯″紡锛團actory锛夊厑璁镐綘鍦ㄤ唬鐮佹墽琛屾椂瀹炰緥鍖栧璞°傚畠涔嬫墍浠ヨ绉颁负宸ュ巶妯″紡鏄洜涓哄畠璐熻矗鈥滅敓浜р濆璞°傚伐鍘傛柟娉曠殑鍙傛暟鏄 浣犺鐢熸垚鐨勫璞″搴旂殑绫诲悕绉般
Example #1 璋冪敤宸ュ巶鏂规硶锛堝甫鍙傛暟锛
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<code><?php
class Example
{
// The parameterized factory method
public static function factory($type)
{
if (include_once 'Drivers/' . $type . '.php') {
$classname = 'Driver_' . $type;
return new $classname;
} else {
throw new Exception ('Driver not found');
}
}
}
?></code>
|
鎸変笂闈㈢殑鏂瑰紡鍙互鍔ㄦ佸姞杞絛rivers銆傚鏋淓xample绫绘槸涓涓暟鎹簱鎶借薄绫伙紝閭d箞 鍙互杩欐牱鏉ョ敓鎴怣ySQL鍜 SQLite椹卞姩瀵硅薄锛
1
2
3
4
5
6
7
|
<code><?php
// Load a MySQL Driver
$mysql = Example::factory('MySQL');
// Load a SQLite Driver
$sqlite = Example::factory('SQLite');
?></code>
|
鍗曚緥
鍗曚緥妯″紡锛圫ingleton锛夌敤浜庝负涓涓被鐢熸垚涓涓敮涓鐨勫璞°傛渶甯哥敤鐨勫湴鏂规槸鏁版嵁搴撹繛鎺ャ 浣跨敤鍗曚緥妯″紡鐢熸垚涓涓璞″悗锛岃瀵硅薄鍙互琚叾瀹冧紬澶氬璞℃墍浣跨敤銆
Example #2 鍗曚緥妯″紡
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
|
<code><?php
class Example
{
// 淇濆瓨绫诲疄渚嬪湪姝ゅ睘鎬т腑
private static $instance;
// 鏋勯犳柟娉曞0鏄庝负private锛岄槻姝㈢洿鎺ュ垱寤哄璞
private function __construct()
{
echo 'I am constructed';
}
// singleton 鏂规硶
public static function singleton()
{
if (!isset(self::$instance)) {
$c = __CLASS__;
self::$instance = new $c;
}
return self::$instance;
}
// Example绫讳腑鐨勬櫘閫氭柟娉
public function bark()
{
echo 'Woof!';
}
// 闃绘鐢ㄦ埛澶嶅埗瀵硅薄瀹炰緥
public function __clone()
{
trigger_error('Clone is not allowed.', E_USER_ERROR);
}
}
?></code>
|
杩欐牱鎴戜滑鍙互寰楀埌涓涓嫭涓鏃犱簩鐨凟xample绫荤殑瀵硅薄銆
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<code><?php
// 杩欎釜鍐欐硶浼氬嚭閿欙紝鍥犱负鏋勯犳柟娉曡澹版槑涓簆rivate
$test = new Example;
// 涓嬮潰灏嗗緱鍒癊xample绫荤殑鍗曚緥瀵硅薄
$test = Example::singleton();
$test->bark();
// 澶嶅埗瀵硅薄灏嗗鑷翠竴涓狤_USER_ERROR.
$test_clone = clone $test;
?></code>
|
浠ヤ笂灏辨槸PHP璁捐妯″紡鐨勮缁嗗唴瀹癸紝鏇村淇℃伅璇峰叧娉∣D浜戝叾瀹冪浉鍏虫枃绔狅紒