我正在开发一个web应用程序框架,其中一部分包括多个服务,所有服务都实现为单例。它们都扩展自一个Service类,在这个类中实现了单例模式的行为,看起来类似于以下代码:
class Service {
protected static $instance;
public function Service() {
if (isset(self::$instance)) {
throw new Exception('Please use Service::getInstance.');
}
}
public static function &getInstance() {
if (empty(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
}
现在,假设我有一个名为FileService的类,它的实现如下:
class FileService extends Service {
// Lots of neat stuff in here
}
调用FileService::getInstance()方法不能返回我想要的FileService实例,而是返回了Service实例。我猜问题出在Service构造函数中使用的"self"关键字。
有没有其他方法可以实现我想要的效果?虽然单例模式只需要写几行代码,但我仍然希望尽可能避免任何冗余代码。