利用好PHP5.3的新特性,实现单例模式

来源:互联网 发布:乐视视频无法连接网络 编辑:程序博客网 时间:2024/06/03 16:55

5.3以前也可实现,但代码较繁琐, 如下:

class MOrder extends SModel{
    protected static $handle; //单例句柄

    private function __construct(){
       //something
    }

    /**
     * 获取本类单例的方法,公开
     *
     * @return MOrder
     */
    public static function instance() {
        if(self::$handle){
            return self::$handle;
        }

        $class = __CLASS__;
        self::$handle = new $class();
        return self::$handle;
    }

    //otherthing

}


5.3增加延迟静态绑定(这个词真别扭)

代码实现如下

class SModel {
    /**
     * 获取单例句柄,返回具体模型类的实例对象
     */
    protected static function instance() {
        if(static::$handle){
            return static::$handle;
        }
    
        $class = get_called_class();
        static::$handle = new $class();
        return static::$handle;
    }

    //父类something

}


class MGoods extends SModel{
    /**
     * 获取本类单例的方法,公开
     * @return MGoods
     */
    public static function instance(){
        return parent::instance();
    }
    protected static $handle; //单例句柄
    protected function __construct(){
        //something
    }

    //otherthing

}


通过修改,子类的实现代码减少一部分,转由父类实现

实话说,仍很麻烦,如果PHP自己实现singleton就好了.


0 0
原创粉丝点击