PHP設計模式之單例模式

來源:互聯網
上載者:User

  單例模式 :使得類的一個對象成為系統中的唯一執行個體.

  PHP中使用單例模式最常見的就是資料庫操作了。避免在系統中有多個串連資料庫的操作,浪費系統資源的現象,就可以使用單例模式。每次對資料庫操作都使用一個執行個體。

  簡單樣本

  class AClass {

  // 用來儲存自己執行個體

  public static $instance;

  // 私人化建構函式,防止外界執行個體化對象

  private function __construct() {}

  // 私人化複製函數,防止外界複製對象

  private function __clone() {}

  // 靜態方法,單例訪問統一入口

  public static function getInstance() {

  if (!(self::$instance instanceof self)){

  self::$instance = new self();

  }

  return self::$instance;

  }

  // test

  public function test() {

  return "done";

  }

  // 私人化複製函數,防止外界複製對象

  private function __clone() {}

  }

  class BClass extends AClass{

  }

  // 擷取執行個體

  $aclass = AClass::getInstance();

  $bclass = BClass::getInstance();

  // 調用方法

  echo $aclass->test();

  對一些比較大型的應用來說,可能串連多個資料庫,那麼不同的資料庫公用一個對象可能會產生問題,比如串連控制代碼的分配等,我們可以通過給$instance變成數組,通過不同的參數來控制

  簡單樣本

  class DB {

  // 用來儲存自己執行個體

  public static $instance = array();

  public $conn;

  // 私人化建構函式,防止外界執行個體化對象

  private function __construct($host, $username, $password, $dbname, $port) {

  $this->conn = new mysqli($host, $username, $password, $dbname, $port);

  }

  // 靜態方法,單例訪問統一入口

  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);

  }

  // 私人化複製函數,防止外界複製對象

  private function __clone() {}

  //釋放資源

  public function __destruct(){

  $this->conn->close();

  }

 

  }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.