類與物件(PHP5)之九:模式(Patterns)

日期:2006-09-26  作者:喜騰小二  來源:PHPChina


模式是最好的實踐和設計的描述方法。它給普通的編程問題展示一個可變的解決方案。
工廠模式(Factory)
工廠模式允許在執行的時間實例化一個物件。自從工廠模式命名以來,制造一個物件是可能的。

例子 19-23.工廠方法 (Factory Method)
PHP程式碼如下:

php
class Example
{   public static function factory($type)//The factory method
    
{   if (include_once 'Drivers/'.$type.'.php'
         {    
$classname 'Driver_' $type;
            return new 
$classname;
        }else{   
throw new Exception ('Driver not found');  }
    }
}
?> 


在類中允許定義一個磁碟機在不工作時被載入的方法。如果類例子是一個資料庫抽象類,可以象如下這樣載入一個MySQL和SQLite驅動
PHP程式碼如下:

php
 $mysql 
Example::factory('MySQL'); // Load a MySQL Driver
 
$sqlite Example::factory('SQLite'); // Load a SQLite Driver
?> 


單獨模式(Singleton)
單模式適用於需要一個類的單獨介麵的情況。最普通的例子是資料庫連線。這個模式的實現
允許程式設計人員構造一個透過許多其他物件輕鬆地訪問的單獨介麵。
例子
19-24.單模式函式(Singleton Function)
PHP程式碼如下:

php
class Example
{   // Hold an instance of the class
    
private static $instance;
    
private function __construct()//A private constructor;prevents direct creation of object 
    
{   echo 'I am constructed';   }
     
public static function singleton()// The singleton method 
    
{   if (!isset(self::$instance)) 
         {    
$c __CLASS__;
            
self::$instance = new $c;
        }
        return 
self::$instance;
    }   
    
// Example method
    
public function bark() {   echo 'Woof!';   }
    
// Prevent users to clone the instance
    
public function __clone(){   trigger_error('Clone is not allowed.',E_USER_ERROR);  }
}
?> 


允許類實例的一個單獨介麵被重新獲得。
PHP程式碼如下:

php
$test 
= new Example// This would fail because the constructor is private
$test Example::singleton();// This will always retrieve a single instance of the class
$test->bark();
$test_clone clone($test); // This will issue an E_USER_ERROR.
?> 




<<<返回技術中心

技術文章

站內新聞

我要啦免费统计