PHP 单态设计模式

称呼:单态设计模式、单例设计模式、单件设计模式(可别被面试时候问倒了哦)
概念:Singleton(单例)模式主要作用是保证在面向对象编程语言设计编写的程序中,一个类Class只有一个实例存在。
用途:在很多操作中,比如建立目录 数据库连接都需要这样的单线程操作。
实现方法:
     (1)如果想让一个类,只能有一个对象,就要先让这个类不能创建对象,且不能被克隆(__clone),因此需要将构造方法以及克隆方法私有化
     (2)在类中提供一个静态方法,来创建对象
     (3)在类中提供一个静态属性,用于存储实例化对象(如果对象存在,则不再实例化,从而保证对象只被实例化一次)
例子:
class Instance {
  //静态变量保存全局实例
  private static $_instance = null;

  //私有构造函数,防止外界实例化对象
  private function __construct() {
    echo '看我出现几次,就说明我被创建了几次<hr>';
  }

  //私有克隆函数,防止外办克隆对象
  private function __clone() {}

  //静态方法,单例模式统一访问入口
  static public function getInstance() {
    if (is_null(self::$_instance)) {
      self::$_instance = new self();
    }
    return self::$_instance;
  }

}
Instance::getInstance();
Instance::getInstance();
Instance::getInstance();
原文地址:https://www.cnblogs.com/cloudshadow/p/php-singleton.html