[PHP] 单例模式-创建型设计模式

使应用中只存在一个对象的实例,并且使这个单实例负责所有对该对象的调用

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(){
    }
    private function __wakeup(){
    }
}

类型前面的问号表示参数或返回值可为空(null),是PHP7的新特性
例如,?string $str 表示$str的值可以为null或字符串
此用法不只局限于静态类型,类和接口也可使用,例如,?MyInterface

posted @ 2020-10-13 18:42  唯一客服系统开发笔记  阅读(164)  评论(0编辑  收藏  举报