PHP设计模式之单件(Singleton)

<?php
class Singleton{  
 /*私有的实例*/
    private static $instance = NULL; 
    public $message;
    /*私有的构造方法*/
    private function __construct(){  
    }
    static function getInstance(){ 
     /*如果实例不存在的话,则实例化一个新的,否则就用原来的*/
        if(self::$instance == null){  
            self::$instance = new Singleton();  
        }
        return self::$instance;  
    }  
}  
 function Client(){
  $singleton1 = Singleton::getInstance();
  $singleton1->message = "1";
  $singleton2 = Singleton::getInstance();
  $singleton2->message = "2";
  /*可以看出,更改第二个实例的message的时候,第一个的也被改了,证明两个其实是同一个实例*/
  echo $singleton1->message;  
 }
?>
<?php 
 Client();
?>


你可能感兴趣的:(PHP,单件)