note 65352 added to language.oop5.patterns
| From: | lycboy at gmail dot com | Date: | Sat, 29 Apr 2006 10:15:20 +0000 |
| Subject: | note 65352 added to language.oop5.patterns | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-110074@lists.php.net to get a copy of this message | ||
I don't agree to take a class with only static members and static methods as a
'singleton'. According to GoF's book, the singleton pattern means a class that only
have one instance. A class containing only static members and functions still can be instantiated
and extended, it have multiple instances. Consider the code below:
<?php
class StaticTest
{
private static $_test = "aaa";
public static function test()
{
echo self::$_test;
}
}
$obj = new StaticTest();
?>
The code will not report errors(although it's useless). So there can be many instances of the
class.
It's reasonable that there is a class that create and store a unique instance of another class.
Such as:
<?php
class A
{
private $_id = 0;
public function getId()
{
return $this->_id;
}
}
class B
{
private static $_instance;
public static function singleton()
{
if (!isset(self::$_instance)) {
self::$instance = new A();
}
return self::$instance;
}
}
?>
Here class B act as a guard to class A. But as same as the first section, it's useless too!
Unless you can make sure that the users of your class will never find the class A, you
shouldn't make the class you wanna to be unique can be instantiated many times.
So the best way to create a unique instance of a class is that the class save the unique instance
itself. It is the core meaning of singleton pattern. Any information that mentioned here can be
found in the book of GoF. I think it's worth reading the book.
BTW: It's allowed that there are a few of subclasses of a singleton class.
----
Server IP: 66.163.161.117
Probable Submitter: 219.142.118.227
----
X-Spam-Status: No, hits=3.1 required=5.0 tests=DATE_MISSING,FROM_NO_LOWER
autolearn=no version=2.64
----
Manual Page -- http://www.php.net/manual/en/language.oop5.patterns.php
Edit -- http://master.php.net/note/edit/65352
Del: integrated -- http://master.php.net/note/delete/65352/integrated
Del: useless -- http://master.php.net/note/delete/65352/useless
Del: bad code -- http://master.php.net/note/delete/65352/bad+code
Del: spam -- http://master.php.net/note/delete/65352/spam
Del: non-english -- http://master.php.net/note/delete/65352/non-english
Del: in docs -- http://master.php.net/note/delete/65352/in+docs
Del: other reasons-- http://master.php.net/note/delete/65352
Reject -- http://master.php.net/note/reject/65352
Search -- http://master.php.net/manage/user-notes.php