码迷,mamicode.com
首页 > 其他好文 > 详细

单例模式

时间:2017-02-24 23:51:07      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:mode   author   self   cte   common   copy   led   extends   img   

技术分享
/**
 * @author xiaojiang
 * 方式1
 */
class father{
    static $models = [];
    static public function getInstance(){
        $name =  get_called_class();
        if( !isset( self::$models[$name] ) ){
            self::$models[$name] = new $name();
        }
        return self::$models[$name];
    }
    
    public function m1(){
        echo "fm1";
    }
    public function m2(){
        echo "fm2";
    }
}
class child extends father{
    public function m1(){
        echo ‘cm1‘;
    }
}
father::getInstance()->m1();
child::getInstance()->m1();

/**
 * 方式2
 */
 class base{

    static protected  $ins = [];
    
    static public function getInstance(){
        $cName = get_called_class();
        if( !isset(static::$ins[$cName]) ){
            static::$ins[$cName] = new $cName;
        }
        return static::$ins[$cName];
    }
    
    public function m1(){
        return "base m1";
    }
    
    public function m2(){
        return "base m2";
    }
    
}

class cbase extends base{
    
    //static public $ins = null;
    static public function getInstance(){
        return parent::getInstance();
    }
    
    public function m1(){
        return "cbase m1<br>";
    }
    
}


echo base::getInstance()->m1()."<br>";

echo cbase::getInstance()->m1(); 
技术分享

单例模式

标签:mode   author   self   cte   common   copy   led   extends   img   

原文地址:http://www.cnblogs.com/benpaodegegen/p/6440500.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!