美文网首页
PHP设计模式-单例模式

PHP设计模式-单例模式

作者: 木有sky | 来源:发表于2019-02-17 10:08 被阅读0次

适用性

当类只能有一个实例而且客户可以从一个众所周知的访问点访问它时。

当这个唯一实例应该是通过子类化可扩展的,并且客户应该无需更改代码就能使用一个扩展的实例时。

UML

代码示例

CD wed站点出售CD。在访问者购买后要及时更新库存。为了实现这个功能。需要链接MySQL 数据库以及更新CD数量。使用变相对象的方式。可能要创造多个不必要的数据库链接。如下所示,完全可以选择单例模式的数据库链接:

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

    {

        $this->_handle = mysql_connect('localhose','user','pass');

        mysql_select_db('cd',$this->_handle);

    }

    public function updateQuantity($band,$title,$number)

    {

        $query = "update CDS set amount=amount+".intval($number);

        $query .= " where band =' ".mysql_real_escape_string($band)." ' ";

        $query .= " and title =' ".mysql_real_escape_string($title)." ' " ;

        mysql_query($query,$this->_handle);

    }

}

InventoryConnection 类的第一个公共方法 getInstance()的静态方法。这个方法检查$_instance 是否有实例。接下来就是购买CD.

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

    }       

}

通过调用InventoryConnection 的getInstance() 方法来获得这个类的实例。一旦接收实例,就会调用通过调用InventoryConnection 对象updateQuantity()方法指定CD数量减1。

$boughtCDs = array();

$boughtCDs[] = array('band'=>'Never Again','Waste of a Rib');

$boughtCDs[] = array('banc'=>'Therappee','Long Road');

foreach ($boughtCDs as $boughtCD)

{

    $cd = new CD($boughtCD['title'],$boughtCD['banc']);

    $cd->buy();

}

相关文章

  • 2018-04-08php实战设计模式

    一、单例模式 单例模式是最经典的设计模式之一,到底什么是单例?单例模式适用场景是什么?单例模式如何设计?php中单...

  • ThinkPHP设计模式与Trait技术

    阅读原文 设计模式 单例模式 工厂模式 对象注册树 示例 运行 Trait技术 自 PHP 5.4.0 起,PHP...

  • 单例模式Java篇

    单例设计模式- 饿汉式 单例设计模式 - 懒汉式 单例设计模式 - 懒汉式 - 多线程并发 单例设计模式 - 懒汉...

  • 测试文章

    php 设计模式 1.单例模式 单例模式顾名思义,就是只有一个实例。作为对象的创建模式, 单例模式确保某一个类只有...

  • pattern设计模式

  • python中OOP的单例

    目录 单例设计模式 __new__ 方法 Python 中的单例 01. 单例设计模式 设计模式设计模式 是 前人...

  • 单例

    目标 单例设计模式 __new__ 方法 Python 中的单例 01. 单例设计模式 设计模式设计模式 是 前人...

  • 设计模式 - 单例模式

    设计模式 - 单例模式 什么是单例模式 单例模式属于创建型模式,是设计模式中比较简单的模式。在单例模式中,单一的类...

  • 设计模式

    常用的设计模式有,单例设计模式、观察者设计模式、工厂设计模式、装饰设计模式、代理设计模式,模板设计模式等等。 单例...

  • python 单例

    仅用学习参考 目标 单例设计模式 __new__ 方法 Python 中的单例 01. 单例设计模式 设计模式设计...

网友评论

      本文标题:PHP设计模式-单例模式

      本文链接:https://www.haomeiwen.com/subject/solieqtx.html