Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

Chapter 23. Singleton Pattern > Singleton Factory

23.3. Singleton Factory

The factory pattern can be repurposed to turn a class cluster into a singleton factory. In Chapter 22, you saw how a class's initializer can substitute a different class for the one being requested. This same technique can be used to return an existing object as well. To implement the singleton pattern, cripple the initializer so that it returns the same object every time. The code in Listing 23-3 implements a singleton using the class's initializer.

Example 23.3. Singleton Factory Pattern

@interface CommandCenter : NSObject

@end

static CommandCenter* SharedCommandCenter;

@implementation CommandCenter
- (id)init
{
    self = [super init];
    if (self!=nil) {
        if (SharedCommandCenter!=nil)
            return SharedCommandCenter;
        ...
        SharedCommandCenter = self;
    }
    return self;
}

@end


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free 10-Day Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint