素材牛VIP会员
关于PHP单例模式,有一点不明白,求指教!
 错***7  分类:PHP代码  人气:4215  回帖:15  发布于5年前 收藏

首先,我定义个类,实现单例模式:(这里是简单一写,就是个最基本的单例)

class Demo
{
    public static $instance;
    
    private function __Construct()
    {
        //TODO
    }
    
    public static function getInstance()
    {
        if(!self::$instance){
            self::$instance = new static();
        }
        
        return self::$instance;
    }
    
    public function call()
    {
        //其他方法
    }
}

下面有两种方式实例化类:

1.在需要用的地方

$aa = Demo::getInstance();
$bb = Demo::getInstance();
$cc = Demo::getInstance();

这样调用肯定是没问题的,一般情况也是这样初始化。

2.定义一个普通类,写个函数初始化,保存在一个静态变量,如下:

类:

class Demo{
    public function __Construct(){
        //TODO
    }
}

函数:

function get_obj(){
    static $obj;
    if($obj){
        return $obj;
    }else{
        $obj = new Demo;
        return $obj;
    }
}

在需要调用的地方这样写:

$obj = get_obj();
$obj->call();

$obj2 = get_obj();
$obj2->call();

$obj3 = get_obj();
$obj3 = get_obj();

这样不是也只实例化一次这个类吗?

讨论这个帖子(15)垃圾回帖将一律封号处理……

Lv6 码匠
hj***jh 软件测试工程师 5年前#1

单例模式,是一种设计思想实现方式

Lv3 码奴
lo***68 交互设计师 5年前#2

完善的单例应该是这样的

class Foobar {
    static private $instance;
    
    // 禁止外部new Foobar
    private function __construct() {
    }
    
    // 禁止clone $foobar
    private function __clone() {
    }
    
    static public function getInstance() {
        retrun self::$instance
            ?: (self::$instance = new self);
    }
}

如果还要考虑到继承的话

class Foo {
    static private $instances = [];

    protected function __construct() {
    }

    final private function __clone() {
    }

    final static public function getInstance() {
        $class = get_called_class();

        if (!isset(self::$instances[$class])) {
            self::$instances[$class] = new static;
        }

        return self::$instances[$class];
    }
}

class Bar extends Foo {

}

$foo = Foo::getInstance();
$bar = Bar::getInstance();

get_obj()那种写法,也可以达到目的,但无法禁止new和clone,也就无法做到真正的单例

Lv6 码匠
ti***nx 学生 5年前#3

你那样写不符合面向对象思想的,而且你的单例模式也不完整,没有考虑到clone和extends的情况。可以参考下http://www.xtwind.com/design-pattern-singleton.html

Lv1 新人
wx***35 职业无 3年前#4
学习了
上一页12下一页
 文明上网,理性发言!   😉 阿里云幸运券,戳我领取