设计模式 - 创造 - 单例模式

通过单例模式的方法创建的类在当前进程中只有一个实例(根据需要,也有可能一个线程中属于单例)

  • 代码

      // Singleton.php
      namespace Creational\Singleton;
      use Exception;
    
      final class Singleton
      {
          private static ?Singleton $instance = null;
    
          public static function getInstance(): Singleton
          {
              if (static::$instance === null) {
                  static::$instance = new static();
              }
    
              return static::$instance;
          }
    
          private function __construct()
          {
          }
    
          private function __clone()
          {
          }
    
          public function __wakeup()
          {
              throw new Exception("Cannot unserialize singleton");
          }
      }
      // SingletonTest.php
      namespace Tests;
    
      use Creational\Singleton\Singleton;
      use PHPUnit\Framework\TestCase;
    
      final class SingletonTest extends TestCase
      {
          public function testsl()
          {
              $firstCall = Singleton::getInstance();
              $secondCall = Singleton::getInstance();
    
              $this->assertInstanceOf(Singleton::class, $firstCall);
              $this->assertSame($firstCall, $secondCall);
          }
      }
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!