The point is preventing anything else from creating another Singleton. A Singleton is supposed to guarantee that only one instance of the singleton class exists. Ever.
There's nothing wrong with it per se, it's a limitation of this particular implementation. The base Singleton constructor is declared final, so it cannot be overriden. The upshot of which is that any class that extends Singleton cannot override the constructor. This is to prevent someone from creating a subclass that overrides the constructor and makes it public, thus breaking the Singleton pattern. In C++ this can't happen, if a base class has a private constructor then all derived classes can only instantiate themselves. __construct() is still called, it just can't be overridden to take parameters or do anything else.
This is the reason for the Construct() function that can be overridden in sub-classes if the singleton in question requires some kind of initialisation. Although perhaps a semantically better name for the function would have been Init().
This of course leads to the problem of: what if I want to pass in parameters to a singleton constructer. My second post above was my best effort to solve that problem. With that change, you just pass in the extra parameters after the class name when you call GetInstance().
I'm beginning to regret that second post now. Singletons created on first access should control their own construction. The simplest way to do this is to keep all constructors parameter free.
Of course you could decide to not declare the constructor final, but you then have to remember that every class derived from Singleton needs a private constructor to work properly.
To show by example if we do this instead:
PHP Code:
class Singleton
{
...
// No creation or cloning.
private function __construct() { $this->Construct(); }
final private function __clone() {}
...
}
We can also do this:
PHP Code:
<?php
include_once( $_SERVER['DOCUMENT_ROOT'].'/../Include/Singleton.php' );
// A test singleton with a 'Constructer'
class TestSingleton extends Singleton
{
public function __construct( $inVar = 0 )
{
$this->mVar = $inVar;
}
public $mVar;
}
// Instantiate the Test Singleton.
$theTestSingleton = Singleton::GetInstance( 'TestSingleton', 'Hello World!' );
$theOtherSingleton = new TestSingleton( 'Hi Other World!' );
echo $theTestSingleton->mVar.'<br />';
echo $theOtherSingleton->mVar;
?>
This gives the output:
Quote:
Hello World!
Hi Other World!
|
As you can see we have two instances of the class created, and it is therefore not a Singleton.