You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何单例模式采用返回对象的函数而非简单初始化函数?

单例模式的两种实现对比

在本站及其他平台,我常见的单例模式实现写法如下:

<?php

Class Singleton {
    private static $code = null;
    private static $instance = null;
    
    private function __construct() {
        self::$code = 'some_expensive_operation';
    }
    
    public static function getInstance() {
        if ( is_null(self::$instance) ) {
            self::$instance = new Singleton();
        }
     
        return self::$instance;
    }
    
    public static function useCode() {
        echo self::$code;
    }
}

// 使用示例
$object1 = Singleton::getInstance();
$object1::useCode();

?>

不过用常规初始化函数代替构造函数的写法似乎更合理,示例代码如下:

<?php

Class Singleton {
    private static $code = null;
    
    public static function initialize() {
        if ( is_null(self::$code) ) {
            self::$code = 'some_expensive_operation';
        }
    }
    
    public static function useCode() {
        echo self::$code;
    }
}

Singleton::initialize();

// 使用示例
Singleton::useCode();

?>

我更倾向第二种写法,因为它只需要一行初始化代码,不需要临时变量,看起来更简洁。

内容的提问来源于stack exchange,提问作者jstallings

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 10:52:42