PHP设计模式 - 单例模式

2019-04-22 17:29 By "Powerless" 2855 0 1

【一】模式定义

    简单说来,单例模式的作用就是保证在整个应用程序的生命周期中,任何一个时刻,单例类的实例都只存在一个,同时这个类还必须提供一个访问该类的全局访问点。

    常见使用实例:数据库连接器;日志记录器(如果有多种用途使用多例模式);锁定文件。


【二】UML类图

image.png


【三】示例代码

Singleton.php

<?php

namespace DesignPatterns\Creational\Singleton;

/**
 * Singleton类
 */
class Singleton
{
    /**
     * @var Singleton reference to singleton instance
     */
    private static $instance;
    
    /**
     * 通过延迟加载(用到时才加载)获取实例
     *
     * @return self
     */
    public static function getInstance()
    {
        if (null === static::$instance) {
            static::$instance = new static;
        }

        return static::$instance;
    }

    /**
     * 构造函数私有,不允许在外部实例化
     *
     */
    private function __construct()
    {
    }

    /**
     * 防止对象实例被克隆
     *
     * @return void
     */
    private function __clone()
    {
    }

    /**
     * 防止被反序列化
     *
     * @return void
     */
    private function __wakeup()
    {
    }
}


【四】测试代码

Tests/SingletonTest.php

<?php

namespace DesignPatterns\Creational\Singleton\Tests;

use DesignPatterns\Creational\Singleton\Singleton;

/**
 * SingletonTest用于测试单例模式
 */
class SingletonTest extends \PHPUnit_Framework_TestCase
{

    public function testUniqueness()
    {
        $firstCall = Singleton::getInstance();
        $this->assertInstanceOf('DesignPatterns\Creational\Singleton\Singleton', $firstCall);
        $secondCall = Singleton::getInstance();
        $this->assertSame($firstCall, $secondCall);
    }

    public function testNoConstructor()
    {
        $obj = Singleton::getInstance();

        $refl = new \ReflectionObject($obj);
        $meth = $refl->getMethod('__construct');
        $this->assertTrue($meth->isPrivate());
    }
}


注:本文转载自 Laravel学院 ,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责。
如有侵权行为,请联系我们,我们会及时删除。

评 论

View in WeChat

Others Discussion

  • 2016年云计算热词
    Posted on 2019-06-12 17:53
  • PHP没你想的那么差
    Posted on 2021-12-17 15:40
  • Mysql联合索引的最左前缀匹配原则
    Posted on 2018-08-25 15:00
  • 巧用CAS解决数据一致性问题
    Posted on 2019-03-07 11:55
  • 分布式架构之「 数据分布」
    Posted on 2019-11-14 10:00
  • PHP扩展ImageMagick安装
    Posted on 2022-11-11 11:16
  • 通过信鸽来解释HTTPS
    Posted on 2018-10-22 13:56
  • HTTP和HTTPS的区别
    Posted on 2020-08-10 23:00