单例模式

This commit is contained in:
cloud 2022-04-15 04:27:54 +08:00
parent e5a380573b
commit 1b5fe57b9f
3 changed files with 106 additions and 0 deletions

View File

@ -0,0 +1,41 @@
<?php
namespace demo\Creational\Singleton;
class Run extends \bin\Design
{
/**
* 单例模式被公认为是 反面模式,为了获得更好的可测试性和可维护性,请使用『依赖注入模式』。
*
* [反面模式]在软件工程中一个反面模式Anti-pattern Antipattern指的是在实践中明显出现但又低效或是有待优化的设计模式
* 是用来解决问题的带有共同性的不良方法。它们已经经过研究并分类,以防止日后重蹈覆辙,并能在研发尚未投产的系统时辨认出来。
*
* @inheritDoc
*/
public function setDesignName() : string
{
return '单例模式Singleton';
}
/**
* @inheritDoc
*/
public function setDesignRefUrl() : string
{
return 'https://learnku.com/docs/php-design-patterns/2018/Singleton/1494';
}
/**
* @inheritDoc
*/
public function main()
{
$firstCall = Singleton::getInstance();
$secondCall = Singleton::getInstance();
// 判断类型是否一致
dump(Singleton::class instanceof $firstCall);
// 判断是否一样
dump($firstCall === $secondCall);
}
}

View File

@ -0,0 +1,45 @@
<?php
namespace demo\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()
{
}
/**
* 防止反序列化(这将创建它的副本)
*/
public function __wakeup()
{
}
}

View File

@ -0,0 +1,20 @@
<?php
namespace demo\Creational\Singleton\Tests;
use demo\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);
}
}