设计模式–创建性模式–单例模式(Singleton)

  •   
  • 645
  • php
  • 0
  • dodobook
  • 2018/12/13

单例模式优点减少资源浪费

1533884335412488

//只有一个实例,自行创建实例并对外提供这个实例


class Mysql {

    private static $instance;
    
    private function __construct() {
		self::$instance = new PDO("mysql:dbname=testdb;host=127.0.0.1", "root", "root");
    }

    public static function getInstance() {
        if(!(self::$instance instanceof self)){
            self::$instance = new self;
        }
        return self::$instance;
    }

    //防止对象被复制
    public function __clone(){
		trigger_error('Clone is not allowed !');
    }

    //防止反序列化后创建对象
    public function __wakeup() {
		trigger_error('Unserialized is not allowed !');
    }


    public function queryOne() {
    	//.......
    }
}

$mysql = Mysql::getInstance();

$mysql->queryOne();

半山冬雨半生忧,一壶清茶难入喉,山后本是平静地,奈何俗人一身愁!