设计模式(单例)

单例模式是最简单的设计模式,

意图:

  保证一个类仅有一个实例,并提供一个访问它的全局访问点。

适用性:

  只能有一个实例而且客户可以从一个众所周知的访问点访问它时。

  当这个唯一实例应该是通过子类化可扩展的,并且客户应该无需更改代码就能使用一个扩展的实例时。

原理图:

clip_image005

代码实现:

<?php
class Singleton {
//     private static $_instance = array();
    private static $_instance = '';
    public $num = 0;
    public static function getInstance() {
        if ( empty(self::$_instance) ){
            self::$_instance = new self();
        }
//         if ( isset(self::$_instance[]) ){
//             self::$_instance = new self();
//         }
        return self::$_instance;
    }
    
    public function sayName($name = 'zhangsan') {
        echo $name,"<br />";
        $this->num++;
    }
    public function sayNum(){
        echo $this->num,"<br />";
    }
}



$test1 = Singleton::getInstance();
$test1->sayName();      //zhangsn
$test1->sayNum();       //1
$test2 = Singleton::getInstance();
$test2->sayName('lisi');  //lisi
$test2->sayNum();      //2

  

原文地址:https://www.cnblogs.com/faronl/p/4698917.html