开发者

subclassing a singleton

What is the recommended way, if any, to subclass a singleton? For example, I would like to make a subclass of AVAudioSession that adds a couple properties and makes the singleton its own AVAudioSessionDelegate.

Right now, I am overriding sharedInstance to allocate my own class, then call my own class' init method. I am not sure if the other singleton methods need to be protected like a regular singleton, as the super class already is a singleton:

@interface PdAudioSession : AVAudioSession <AVAudioSessionDelegate>

@implementation PdAudioSession

+ (PdAudioSession *)sharedInstance {
    static PdAudioSession *myInstance = nil;
    @synchronized (self) {
        if (!myInstance) {
            myInstance = [[PdAudioSession开发者_开发技巧 alloc] init];
        }
    }
    return myInstance;
}

- (id)init {
    self = [super init];
    if (self) {
        self.delegate = self;
    }
    return self;
}


Rather than subclass the singleton, why not just create a new class that contains an AVAudioSession object. That way you can create it when you initialize your new class, you can add properties to this new class and also provide itself as a delegate.

Composition is the preferred design pattern in Cocoa over subclassing.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜