php设计模式(一)单例设计模式

一、什么是设计模式

设计模式是为了使用通用的解决方案来解决相同的问题而出现的。

二、单例设计模式

通过提供对自身共享实例的访问,单元素设计模式用于限定特定对象只能被创建一次

1、单元素对象的构造函数应当是一个受保护方法,这样就只允许指定类自身创建它的一个实例

2、构造函数还具有一个实际创建、存储和提供新创建实例的公共方法

3、单元素设计模式最常用于构建数据库连接对象。数据库访问对象可以负责创建一个数据库的实例化连接。因为创建与数据库服务器的连接开销很大(需要耗用大量的时间和资源导致效率低下),所以代码应当尽可能不执行这种操作。在大多数情况下,数据库连接的状态在数据被检索之后不再需要保持。

这样限制了实例化对象的个数,可以节省内存

/*
 * 情景:实时处理库存,所以在购买CD后立即更新库存是十分重要的。需要连接MySQL数据库以及更新指定CD的数量。使用面向
 * 对象方式时,可能要创建多个不必要的与数据库的链接。
 * 如下所示,完全可以选择基于单元素设计模式的库存链接
 *
 * */
class InventoryConnection
{
    protected static $_instance = NULL;
    protected $_handle = NULL;

    protected function __construct()
    {
        $this->_handle = mysqli_connect('localhost', 'user', 'pass', 'CD');
    }

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

        return self::$_instance;
    }

    public function updateQuantity($band, $title, $number)
    {
        $query = "update CDS set amount = amount+" . intval($number);
        /*由这里想到,对象中哪些适合声明为成员属性:一些赋值后就固定的参数值,不用每次都传,将其赋值给成员属性,
这样使用起来方便*/
        $query .= " where band=' " . mysqli_real_escape_string($this->_handle, $band). " ' ";
        $query .= " and title=' " . mysqli_real_escape_string($this->_handle, $title). " ' ";

        mysqli_query($this->_handle, $query);
    }
}

class CD
{
    public $_title = '';
    public $_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' => 'Never Again', 'title' => 'Waste of a Rib'];
$boughtCDs[] = ['band' => 'Therapee', 'title' => 'Long Road'];

foreach ($boughtCDs as $boughtCD) {
    $cd = new CD($boughtCD['title'], $boughtCD['band']);
    $cd->buy();
}
/*
 * 在这个示例中,$boughtCDs数组表示来自购物车的商品项。针对每个被购买的CD都打开一个与数据库的新连接并不是一个好做法。
 * 当某个对象的实例化在整个代码流中只允许发生一次时,最佳的做法是使用单例设计模式
 * */

猜你喜欢

转载自blog.csdn.net/hrbsfdxzhq01/article/details/88840676