单例模式
Singleton.h
#import <Foundation/Foundation.h>
@interface Singleton : NSObject
+ (Singleton *)sharedInstance;
- (void)print;
@end
Singleton.m
#import "Singleton.h"
@implementation Singleton
+ (Singleton *)sharedInstance {
static Singleton *_sharedInstance = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_sharedInstance = [[self alloc] init];
});
return _sharedInstance;
}
- (void)print{
NSLog(@"The Singleton Pattern");
}
@end
main.m
#import <Foundation/Foundation.h>
#import "Singleton.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
[[Singleton sharedInstance] print];
}
return 0;
}
注意:因为Objective-C的方法并没有private和public的概念,在任何时间任何对象之间消息都能被传递。因此上面的例子Singleton对象仍然能用init方法创建。
如果一定要使得init方法失效,来至http://stackoverflow.com/questions/195078/is-it-possible-to-make-the-init-method-private-in-objective-c 的解答方案。
网友评论