单例模式(Singleton)
目的
在应用程序调用的时候,只能获得一个对象实例。
一个类只允许创建一个对象(实例)。
用处
处理资源访问冲突、表示全局唯一类
代码
<?php
namespace DesignPatterns\Creational\Singleton;
class Singleton
{
static $instance;
public static function getInstance()
{
if (empty(static::$instance)) {
static::$instance = new static();
}
$instance = static::$instance;
return $instance;
}
private function __construct()
{
}
private function __clone()
{
}
private function __wakeup()
{
}
}
<?php
namespace 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);
}
}