Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
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.
@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 |