抽象单例模式类

Sho*_*hoe 1 php oop singleton

我正在努力实现以下目标:

使用这个一般的单例类:

abstract class Singleton {

    private static $instance = null;

    public static function self()
    {
      if(self::$instance == null)
      {   
         $c = __CLASS__;
         self::$instance = new $c;
      }

      return self::$instance;
    }
}
Run Code Online (Sandbox Code Playgroud)

我很想能够创建Singleton具体类,例如:

class Registry extends Singleton {
    private function __construct() {}
    ...
}
Run Code Online (Sandbox Code Playgroud)

然后将它们用作:

Registry::self()->myAwesomePonyRelatedMethod();
Run Code Online (Sandbox Code Playgroud)

但遗憾的__CLASS__是,因为SingletonPHP无法实例化抽象类而导致致命错误.但事实是我希望实例化Registry(例如).

所以我试过get_class($this)但是作为一个静态类,Singleton没有$ this.

我能做些什么才能让它发挥作用?

Gor*_*don 5

来自我的Slides Singletons的简单代码 - 为什么它们很糟糕以及如何从应用程序中消除它们:

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()
    {}
}
Run Code Online (Sandbox Code Playgroud)

那你可以做

class A extends Singleton
{
    protected static $instance;
}
Run Code Online (Sandbox Code Playgroud)

如果需要init在扩展类中执行其他设置逻辑覆盖.

另请参阅PHP中是否存在具有数据库访问权限的单例用例?

  • @Gordon,你刚刚破坏了我的项目构想.多么残忍!我之前喜欢过Singleton,现在我读了所有关于它们的坏事:(.所以基本上要避免它们我应该使用依赖注入模式? (2认同)