I want to define a Singleton base type from which the user will derive his classes, so this is what I thought:
interface SingletonInterface {
public static function getInstance();
}
abstract class SingletonAbstract implements SingletonInterface {
abstract protected function __construct();
final private function __clone() {}
}
But using this aproach the us开发者_如何学Goer may implement this singleton...
class BadImpl implements SingletonInterface {
public static function getInstance() {
return new self;
}
}
What would be your aproach?
Remember PHP doesn't allow multiple inheritance so you must carefully choose what you base your classes on. Singleton is so easy to implement it's probably better to let each class define it. Beware also that private fields are not ported to descendant classes and therefore you can have two different fields with the same name.
I am using this code for creating a Singleton:
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() {}
}
This is using of this pattern:
class Example extends Singleton {
...
}
$oExample1 = Example::getInstance();
$oExample2 = Example::getInstance();
if(is_a( $oExample1, 'Example' ) && $oExample1 === $oExample2){
echo 'Same';
} else {
echo 'Different';
}
First of all: if you have so much Singletons over the project then you probably mess up something on projection level
Second of all: Singleton should be used there, and only there, where more that one instance of a class makes totally no sense or might cause some errors
Finally: the inheritance ain't designed to reduce the amount of code
You can now use traits, but do you need so much singletons ?
精彩评论