抽象单例模式类 [英] Abstract Singleton pattern class
问题描述
我正在努力实现以下目标:
I'm trying to achieve the following goal:
使用此常规单例类:
abstract class Singleton {
private static $instance = null;
public static function self()
{
if(self::$instance == null)
{
$c = __CLASS__;
self::$instance = new $c;
}
return self::$instance;
}
}
我很希望能够创建Singleton具体类,例如:
I'd love to be able to create Singleton concrete class such as:
class Registry extends Singleton {
private function __construct() {}
...
}
,然后将它们用作:
Registry::self()->myAwesomePonyRelatedMethod();
但是显然地,__CLASS__
旨在作为Singleton
,因此发生致命错误,有关PHP无法实例化抽象类.但事实是,我希望实例化Registry(例如).
But obliviously __CLASS__
is intended as Singleton
so a fatal error occurs about PHP not being able to instantiate an abstract class. But the truth is that I want Registry (for example) to be instantiated.
所以我尝试使用get_class($this)
,但作为静态类,Singleton没有$ this.
So I tried with get_class($this)
but being a static class, Singleton has no $this.
我该怎么做才能使其正常工作?
What could I do to make it work?
推荐答案
我的幻灯片中的删节代码 PHP中的子句-为什么它们不好,以及如何从应用程序中消除它们:
Abridged code from my Slides Singletons in PHP - Why they are bad and how you can eliminate them from your applications:
abstract class Singleton
{
public static function getInstance()
{
return isset(static::$instance)
? static::$instance
: static::$instance = new static();
}
final private function __construct()
{
static::init();
}
final public function __clone() {
throw new Exception('Not Allowed');
}
final public function __wakeup() {
throw new Exception('Not Allowed');
}
protected function init()
{}
}
那你就可以做
class A extends Singleton
{
protected static $instance;
}
如果需要执行其他设置逻辑,请覆盖扩展类中的init
.
If you need to do additional setup logic override init
in the extending class.
这篇关于抽象单例模式类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!