邢栋博客

邢栋博客,Action博客,记录工作和生活中的点点滴滴

php设计模式之单例模式简单事例
<?php

//单例模式
class Singleton
{
	/**
	 * @var 这个类的"单例"
	 */
	private static $instance;

	/**
	 * 防止在这个类之外new这个类
	 */
	private function __construct()
	{
	}

	/**
	 * @return 返回这个类的单例
	 */
	public static function getInstance()
	{
		if(self::$instance === null){
			self::$instance == new self();
		}
		return self::$instance;
	}

	/**
     * @return void 把 clone 方法声明为 private,防止克隆单例
     */
    private function __clone()
    {
    }

     /**
     * @return void 把反序列化方法声明为 private,防止反序列化单例
     */
    private function __wakeup()
    {
    }

}

class SingletonChild extends Singleton
{
}

$obj = Singleton::getInstance();
var_dump($obj === Singleton::getInstance());             // bool(true)

$anotherObj = SingletonChild::getInstance();
var_dump($anotherObj === Singleton::getInstance());      // bool(true)

var_dump($anotherObj === SingletonChild::getInstance()); // bool(true)

?>

单例模式是非常有用的,特别是我们需要确保在整个请求的声明周期内只有一个实例存在。 典型的应用场景是,当我们有一个全局的对象(比如配置类)或一个共享的资源(比如事件队列)时。

php设计模式之单例模式简单示例
<?php
//单例模式 
class Singleton {

    private static $instance=null;
    private $value=null;
    
    private function __construct($value) {
        $this->value = $value;
    }

    public static function getInstance() {
        //echo self::$instance."<br/>";
        if ( self::$instance == null ) {
            echo "<br>new<br>";
            self::$instance = new Singleton("values");
        } else {
            echo "<br>old<br>";
        }
        return self::$instance;
    }
}

$x = Singleton::getInstance();
var_dump($x); // returns the new object


$y = Singleton::getInstance();
var_dump($y); // returns the existing object


?>


最新微语