W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
注:?jiǎn)卫J娇赡鼙徽J(rèn)為是一種“反模式”。為了獲得更好的可測(cè)試性和可維護(hù)性,建議使用依賴注入。
讓應(yīng)用只存在一個(gè)對(duì)象的實(shí)例,處理所有的調(diào)用。
Singleton.php
<?php
declare(strict_types=1);
namespace DesignPatterns\Creational\Singleton;
use Exception;
final class Singleton
{
private static ?Singleton $instance = null;
/**
* gets the instance via lazy initialization (created on first usage)
*/
public static function getInstance(): Singleton
{
if (static::$instance === null) {
static::$instance = new static();
}
return static::$instance;
}
/**
* is not allowed to call from outside to prevent from creating multiple instances,
* to use the singleton, you have to obtain the instance from Singleton::getInstance() instead
*/
private function __construct()
{
}
/**
* prevent the instance from being cloned (which would create a second instance of it)
*/
private function __clone()
{
}
/**
* prevent from being unserialized (which would create a second instance of it)
*/
public function __wakeup()
{
throw new Exception("Cannot unserialize singleton");
}
}
Tests/SingletonTest.php
<?php declare(strict_types=1); 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); } }
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: