PHP設計模式之單例模式

字號:


    單例模式 :使得類的一個對象成為系統(tǒng)中的唯一實例.
    PHP中使用單例模式最常見的就是數(shù)據(jù)庫操作了。避免在系統(tǒng)中有多個連接數(shù)據(jù)庫的操作,浪費系統(tǒng)資源的現(xiàn)象,就可以使用單例模式。每次對數(shù)據(jù)庫操作都使用一個實例。
    簡單示例
    class AClass {
    // 用來存儲自己實例
    public static $instance;
    // 私有化構(gòu)造函數(shù),防止外界實例化對象
    private function __construct() {}
    // 私有化克隆函數(shù),防止外界克隆對象
    private function __clone() {}
    // 靜態(tài)方法,單例訪問統(tǒng)一入口
    public static function getInstance() {
    if (!(self::$instance instanceof self)){
    self::$instance = new self();
    }
    return self::$instance;
    }
    // test
    public function test() {
    return "done";
    }
    // 私有化克隆函數(shù),防止外界克隆對象
    private function __clone() {}
    }
    class BClass extends AClass{
    }
    // 獲取實例
    $aclass = AClass::getInstance();
    $bclass = BClass::getInstance();
    // 調(diào)用方法
    echo $aclass->test();
    對一些比較大型的應用來說,可能連接多個數(shù)據(jù)庫,那么不同的數(shù)據(jù)庫公用一個對象可能會產(chǎn)生問題,比如連接句柄的分配等,我們可以通過給$instance變成數(shù)組,通過不同的參數(shù)來控制
    簡單示例
    class DB {
    // 用來存儲自己實例
    public static $instance = array();
    public $conn;
    // 私有化構(gòu)造函數(shù),防止外界實例化對象
    private function __construct($host, $username, $password, $dbname, $port) {
    $this->conn = new mysqli($host, $username, $password, $dbname, $port);
    }
    // 靜態(tài)方法,單例訪問統(tǒng)一入口
    public static function getInstance($host, $username, $password, $dbname, $port) {
    $key = $host.":".$port;
    if (!(self::$instance[$key] instanceof self)){
    self::$instance[$key] = new self($host, $username, $password, $dbname, $port);#實例化
    }
    return self::$instance[$key];
    }
    //query
    public function query($ql) {
    return $this->conn->query($sql);
    }
    // 私有化克隆函數(shù),防止外界克隆對象
    private function __clone() {}
    //釋放資源
    public function __destruct(){
    $this->conn->close();
    }
    }