【问题标题】:is it possible to define a interface Singleton in PHP?是否可以在 PHP 中定义接口 Singleton?
【发布时间】:2010-08-19 04:32:48
【问题描述】:

我想定义一个 Singleton 基类型,用户将从中派生他的类,所以这是我的想法:


interface SingletonInterface {
    public static function getInstance();
}

abstract class SingletonAbstract implements SingletonInterface {
    abstract protected function __construct();
    final private function __clone() {}
}

但是使用这种方法,用户可以实现这个单例...


class BadImpl implements SingletonInterface {
    public static function getInstance() {
        return new self;
    }
}

你的方法是什么?

【问题讨论】:

标签: php oop singleton


【解决方案1】:

我正在使用此代码来创建单例:

abstract class Singleton {

    private static $_aInstance = array();


    private function __construct() {}

    public static function getInstance() {

       $sClassName = get_called_class(); 

       if( !isset( self::$_aInstance[ $sClassName ] ) ) {

          self::$_aInstance[ $sClassName ] = new $sClassName();
       }
       $oInstance = self::$_aInstance[ $sClassName ];

       return $oInstance;
    }

    final private function __clone() {}
}

这是使用这种模式:

class Example extends Singleton {
   ...
}

$oExample1 = Example::getInstance();
$oExample2 = Example::getInstance();

if(is_a( $oExample1, 'Example' ) && $oExample1 === $oExample2){

    echo 'Same';

} else {

    echo 'Different';
}

【讨论】:

  • 我想过这种方法,但它有一些缺点.. 1. 需要 PHP 5.3 2. 你的类充当 SingletonContainer 3. 派生类被认为是不同的 4. 你正在调用构造函数 但是它的优点是您只需要扩展该类即可拥有单例
【解决方案2】:

请记住 PHP 不允许多重继承,因此您必须仔细选择您的类所基于的内容。 Singleton 很容易实现,最好让每个类都定义它。 另请注意,私有字段不会移植到后代类,因此您可以拥有两个具有相同名称的不同字段。

【讨论】:

    【解决方案3】:

    首先:如果您在项目中有这么多单例,那么您可能会在投影级别上搞砸一些事情

    第二点:单例应该用在那里,而且只有在那里,一个类的多个实例完全没有意义或可能导致一些错误

    最后:继承并不是为了减少代码量而设计的

    【讨论】:

      【解决方案4】:

      你现在可以使用特征,但你需要这么多单例吗?

      【讨论】:

        猜你喜欢
        • 2020-03-08
        • 2012-10-02
        • 2012-12-07
        • 1970-01-01
        • 2016-02-26
        • 2014-03-01
        • 2016-01-04
        • 2011-01-21
        相关资源
        最近更新 更多