Design Patterns – Objective-C – Singleton
After moving from Java into Objective-C world you will notice that some things are not that straight as you could expect. One of these is a implementation of Singleton pattern. In Java and C++ you can easily restrict object creation via private constructor. In Objective-C, you have to deal with it slightly different.
// Singleton declaration - Singleton.h
#import <Foundation/Foundation.h>
@interface Singleton : NSObject {
// we don't need instance variables
}
// we have to overwrite alloc
+ (id) alloc;
// and new - these are responsible for
// object creation
+ (id) new;
+ (Singleton*) getInstance;
// getMessage method is the only instance method.
// This is what Singleton does
- (NSString*) getMessage;
@end
// Singleton definition - Singleton.m
#import "Singleton.h"
@implementation Singleton
// we need static variable for keeping the track
// of Singleton instance. We want to keep it
// "secret", that's why we have to put into
// implementation file
static Singleton *instance = nil;
// the only way of bringing Singleton to live
+(Singleton*) getInstance {
if(instance == nil) {
instance = [[super alloc] init];
}
return instance;
}
// you can't call alloc method directly
+(id) alloc {
NSLog(@"alloc is not possible");
@throw ([NSException
exceptionWithName: @"alloc is not possible "
reason: @"Singleton class doesn't "
"provide explicite allocation"
userInfo: nil ]);
}
// you can't call new method directly
+(id) new {
NSLog(@"new is not possible");
@throw ([NSException
exceptionWithName: @"new is not possible "
reason: @"Singleton class doesn't provide"
"explicite allocation"
userInfo: nil ]);
}
// this is Singleton's API
-(NSString*) getMessage {
return @"Hello from Singleton";
}
@end
April 14th, 2011 in
main entries