为何单例模式采用返回对象的函数而非简单初始化函数?
单例模式的两种实现对比
在本站及其他平台,我常见的单例模式实现写法如下:
<?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
相关产品推荐
相关产品推荐

