单例模式(Singleton)

未匹配的标注

单例模式被公认为是 反面模式,为了获得更好的可测试性和可维护性,请使用『依赖注入模式』。

1.8.1. 目的

在应用程序调用的时候,只能获得一个对象实例。

1.8.2. 例子

  • 数据库连接
  • 日志 (多种不同用途的日志也可能会成为多例模式)
  • 在应用中锁定文件 (系统中只存在一个 ...)

1.8.3. UML 类图

file

1.8.4. 代码部分

你也可以在 GitHub 中查看

Singleton.php


<?php

namespace DesignPatterns\Creational\Singleton;

final class Singleton
{
    /**
    * @var Singleton
    */
    private static $instance;

    /**
    * 通过懒加载获得实例(在第一次使用的时候创建)
    */
    public static function getInstance(): Singleton
    {
        if (null === static::$instance) {
            static::$instance = new static();
        }

        return static::$instance;
    }

    /**
    * 不允许从外部调用以防止创建多个实例
    * 要使用单例,必须通过 Singleton::getInstance() 方法获取实例
    */
    private function __construct()
    {
    }

    /**
    * 防止实例被克隆(这会创建实例的副本)
    */
    private function __clone()
    {
    }

    /**
    * 防止反序列化(这将创建它的副本)
    */
    private function __wakeup()
    {
    }
}

1.8.5. 测试

Tests/SingletonTest.php


<?php

namespace DesignPatterns\Creational\Singleton\Tests;

use DesignPatterns\Creational\Singleton\Singleton;
use PHPUnit\Framework\TestCase;

class SingletonTest extends TestCase
{
    public function testUniqueness()
    {
        $firstCall = Singleton::getInstance();
        $secondCall = Singleton::getInstance();

        $this->assertInstanceOf(Singleton::class, $firstCall);
        $this->assertSame($firstCall, $secondCall);
    }
}

本文章首发在 LearnKu.com 网站上。

本译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

原文地址:https://learnku.com/docs/php-design-patt...

译文地址:https://learnku.com/docs/php-design-patt...

上一篇 下一篇
贡献者:5
讨论数量: 3
发起讨论 查看所有版本


yzq6431
请教一个问题,使用单列模式
0 个点赞 | 2 个回复 | 分享 | 课程版本 2018
Cellophane
new static 和 new static () 有什么区别
0 个点赞 | 1 个回复 | 问答 | 课程版本 2018