Re: Is Apple's singleton sample code correct?
Re: Is Apple's singleton sample code correct?
- Subject: Re: Is Apple's singleton sample code correct?
- From: Shawn Erickson <email@hidden>
- Date: Sat, 26 Nov 2005 07:56:03 -0800
On Nov 26, 2005, at 7:21 AM, David Gimeno Gost wrote:
mmalcolm crawford <email@hidden> wrote:
Can you point me to any document describing the singleton design
pattern saying that a singleton should never be deallocated or
destroyed?
<http://developer.apple.com/cgi-bin/search.pl?
q=singleton&site=default_collection>
I already did that search before starting this discussion and I
haven't found anything there stating that a singleton should never
be deallocated. Actually, I would consider it a bug if I found it
because there is nothing in the singleton design pattern requiring
it to never be destroyed and there are indeed reasons why you may
want to actually be allowed to destroy it when appropriate.
In a vast majority of implementations a singleton is implemented to
do lazy allocation and only once in a given process or is allocated
once at some initialization step up front in process initialization.
You can find countless examples of this in Java, C++, etc. coding
examples.
It is the presumed behavior when talking about singletons in the
general case so that is the perspective Mmalcolm and myself are
talking from. It appears that in this case you want to allow for
singleton deallocation when the singleton is not needed (which is one
of many variations in implementation that you could do, which you do
depends on the intent and paradigm the singleton lives under).
(the following written quickly in Mail.app, so typos possible)
So if you want to allow for singleton deallocation when no one needs
it then...
+ (id) allocWithZone: (NSZone*) zone
{
@synchronized( self ) {
if ( sharedGizmoManager == nil ) {
sharedGizmoManager = [super allocWithZone: zone];
} else {
[sharedGizmoManager retain];
}
}
return sharedGizmoManager;
}
-dealloc {
@synchronized( [MyGizmoManager class] ) {
sharedGizmoManager = nil;
}
[super dealloc];
}
...or when you want it to be lazily allocated and live for the life
of the process...
+ (id) allocWithZone: (NSZone*) zone
{
@synchronized( self ) {
if ( sharedGizmoManager == nil ) {
sharedGizmoManager = [super allocWithZone: zone];
}
}
return [sharedGizmoManager retain];
}
-dealloc {
// note error is some way or override release/retain to prevent
}
...or if you want to reduce overhead in allocWithZone...
+ initialize {
sharedGizmoManager = [super allocWithZone: zone];
}
+ (id) allocWithZone: (NSZone*) zone
{
return [sharedGizmoManager retain];
}
-dealloc {
// note error is some way or override release/retain to prevent
}
etc.
-Shawn
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden