|
Posted by Oli Filth on 01/15/06 06:31
FluffyCat said the following on 15/01/2006 04:03:
> On Sat, 14 Jan 2006 03:07:54 GMT, Oli Filth <catch@olifilth.co.uk>
> wrote:
>
>> FluffyCat said the following on 14/01/2006 00:20:
>>> To add to my growing library of Design Patterns in PHP 5 I have
>>> written what I think is a good example of the Singleton Pattern.
>>>
>>> http://www.fluffycat.com/PHP-Design-Patterns/Singleton/
>>>
>> Unfortunately, this is not a good example of a singleton system.
>>
>> You have a class (BookSingleton) with a public constructor, so there's
>> nothing to stop someone creating multiple BookSingleton objects with
>> multiple "new BookSingleton()" calls.
>>
>> To solve this problem, you need to make the constructor private, and the
>> borrowBook() method static.
>
> Good call on the private constructor and static borrowBook() method,
> that really tightens the class up.
>
Another point to make is that the returnBook() method is currently
pointless. Not only should it be static, but even if it were static, it
would serve no purpose.
Imagine the following code:
$book = BookSingleton::borrowBook();
BookSingleton::returnBook();
// umm, $book still refers to the BookSingleton instance...
To utilise a "returning" feature correctly, you would actually need to
hook onto the object destructor, rather than calling a method
explicitly. However, this is also impossible, as you maintain a static
reference to the object, so it will never get destructed.
Therefore, any attempt at "returning" the singleton object is futile.
--
Oli
Navigation:
[Reply to this message]
|