Singleton design pattern [duplicate]
Possible Duplicate:
W开发者_Python百科hat's the correct method to subclass a singleton class in Objective -C?
@implementation Singleton
- (id)init
{
self = [super init];
if (self) {
// Initialization code here.
}
return self;
}
+(Singleton *)singleton
{
static Singleton * singleton;
if (singleton == nil)
{
singleton =[[Singleton alloc]init];
}
return singleton;
}
@end
Now so far so good.Actually, the init part should be private. But I'll worry about that later.
Now, say I want to subclass the singleton class. How should I modify it?
Also let's see the code here:
+(Singleton *)singleton
{
static Singleton * singleton;
if (singleton == nil)
{
singleton =[[Singleton alloc]init];
}
return singleton;
}
I should modify that to
+(self *)singleton
{
static self * singleton;
if (singleton == nil)
{
singleton =[[self alloc]init];
}
return singleton;
}
So that the singleton method always return the subclass rather than the parent class
Well I got compile error
Now I know a subclass is a "parent". So subclassing a singleton doesn't make sense.
What about if I do not need a strict singleton.
I want
@interface classA: singleton @interface classB: singelton
to all have a singleton method that refer to a single instance of classA and classB?
As duffymo mentions in his comments subclassing a singleton doesn't make sense. Let me try to explain.
Let's say you make two different subclasses both inheriting from your singleton base class. When you instance each of them, only the first will actually create an instance (as this is the point of a singleton). The second subclass instance will not get instantiated. However, the functionality added in the subclasses will get instanced in each seperate subclass. It's getting messy as you might see :-)
Hope this helps...
Regards
精彩评论