设计模式 单例模式

转自:https://github.com/domnikl/DesignPatternsPHP

 1 final class Singleton
 2 {
 3     private static ?Singleton $instance = null;
 4 
 5     public static function getInstance(): Singleton
 6     {
 7         if (static::$instance === null) {
 8             static::$instance = new static();
 9         }
10 
11         return static::$instance;
12     }
13 
14     private function __construct()
15     {
16     }
17 
18     private function __clone()
19     {
20     }
21 
22     private function __wakeup()
23     {
24     }
25 }

 

 1 class SingletonTest extends TestCase
 2 {
 3     public function testUniqueness()
 4     {
 5         $firstCall = Singleton::getInstance();
 6         $secondCall = Singleton::getInstance();
 7 
 8         $this->assertInstanceOf(Singleton::class, $firstCall);
 9         $this->assertSame($firstCall, $secondCall);
10     }
11 }

 

posted @ 2020-05-26 20:18  是的哟  阅读(108)  评论(0编辑  收藏  举报