單例設計模式

<?php
//通過提供對自身共享實例的訪問,單例設計模式用於限制特定對象只能被創建一次。
class InventoryConnection{
    protected static $_instance = null;
    protected $_handle = null;

    public static function getInstance(){
        if(!self::$_instance instanceof self){
            self::$_instance = new self;
        }
        return self::$_instance;
    }

    protected function __construct(){
        echo 'connect mysql'.PHP_EOL;
    }

    public function updateQuantity($band, $title, $number){
        $query = "UPDATE CDs SET amount=amount+'".intval($number)."'";
        $query .= "WHERE band='".addslashes($band)."'";
        $query .= "AND title='".addslashes($title)."'";
        echo $query.PHP_EOL;
    }
}

class CD{
    protected $_title = '';
    protected $_band = '';

    public function __construct($title, $band){
        $this->_title = $title;
        $this->_band = $band;
    }

    public function buy(){
        $inventory = InventoryConnection::getInstance();
        $inventory->updateQuantity($this->_band, $this->_title, -1);
    }
}

$boughtCDs = [];
$boughtCDs[] = ['band' => 'fenghuangchuanqi', 'title' => 'zuixuanminzufeng'];
$boughtCDs[] = ['band' => 'TFBOYS', 'title' => 'zuoshouyoushou'];
foreach($boughtCDs as $boughtCD){
    $cd = new CD($boughtCD['title'], $boughtCD['band']);
    $cd->buy();
}
//當某個對象的實例化在整個代碼流中只允許發生一次時,最佳的做法是使用單例設計模式。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章