DanceSmile / dancesmile.github.io

dancesemile's github pages
4 stars 1 forks source link

设计模式 #9

Open DanceSmile opened 6 years ago

DanceSmile commented 6 years ago
/**
*  单例模式 
*/  
class Single 
{
    //  类实例
    private static $instance = null;

    // 防止外部实例化
    private function __construct()  {}

    // 防止外部克隆
    private function __clone() {}

    // 内部实例化对象,单例防止多次实例化
    public static function getInstance()
    {
        if( !(static::$instance instanceof self )  )
        {
            static::$instance = new Single();
        }
        return static::$instance;
    }

}

$single1 =  Single::getInstance();
var_dump($single1);

$single2 =  Single::getInstance();
var_dump($single2);

if( $single1  === $single2 ){
    echo "===";
}