PHP设计模式 - 单例模式

2019-04-22 17:29 By "Powerless" 2851 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

  • 初识七层、五层、四层网络协议
    Posted on 2021-04-09 16:52
  • 投票通过,PHP 8 确认引入 Union Types 2.0
    Posted on 2019-11-18 22:22
  • Linux工具 - NM目标文件格式分析
    Posted on 2019-04-24 10:29
  • PHP扩展安装
    Posted on 2019-06-24 11:28
  • Redis各种数据类型的使用场景举例分析【三】
    Posted on 2018-11-22 17:00
  • ACID原则
    Posted on 2020-12-17 16:36
  • PHP7不兼容性
    Posted on 2018-03-07 15:59
  • MySQL分组
    Posted on 2019-11-18 14:00