note 53483 added to language.oop5.patterns
| From: | traxeradgmx dot net at osu1 dot php dot net | Date: | Thu, 02 Jun 2005 22:29:29 +0000 |
| Subject: | note 53483 added to language.oop5.patterns | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-89832@lists.php.net to get a copy of this message | ||
In response to Richard Quadling's response to Scott Mattock's response to Jimmy Paterson
...
The singleton pattern is a /pattern/, not a class. There is no way to move the whole functionality
of 'being a singleton' into a common base class, it was not intended that way. There is no
point in adding features to derived classes, other than for internal use, either. Furthermore, when
I derive two classes from Singleton, the singleton is not really a singleton anymore. Considering
this, I think your implementation of Singleton and SubClass (i.e your correction to Scott
Mattock's) is the one that most closely matches the intention of GOF. You can allow sublasses
of SubClass, though:
<?php
class Singleton {
private static $instance;
public static function singleton($class = __CLASS__) {
if (!isset(self::$instance))
self::$instance = new $classname;
return self::$instance;
}
}
class SubClass extends Singleton {
public static function singleton($class = __CLASS__) {
return parent::singleton($class);
}
}
class SubSubClass extends SubClass {
public static function singleton($class = __CLASS__) {
return parent::singleton($class);
}
}
?>
This even works with php4 if you
1. move the Singleton::$instance into function Singleton::singleton,
2. get rid of the unsuported keywords and
3. rename the Singleton::singleton method (so as not to be a constructor).
So no real imporvement here, except for the added protection of not beeing able to create objects
explicitly.
----
Manual Page -- http://www.php.net/manual/en/language.oop5.patterns.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+53483
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+53483&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+53483&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+53483&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+53483&report=yes&reason=useless
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+53483&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+53483&report=yes
Search -- http://master.php.net/manage/user-notes.php