Sian 发表于 2014-2-1 21:38:54

第二十七讲:Objective-C设计模式之单例

本帖最后由 Sian 于 2014-2-1 21:40 编辑

单例,即全局变量
ThemeManager.h
//
//ThemeManager.h
//ThemeManager
//
//Created by yusian on 14-2-1.
//Copyright (c) 2014年 yusian. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface ThemeManager : NSObject

@property (nonatomic, retain) NSString *name;

+ (id) sharedThemeManager;

@end
ThemeManager.m
//
//ThemeManager.m
//ThemeManager
//
//Created by yusian on 14-2-1.
//Copyright (c) 2014年 yusian. All rights reserved.
//

#import "ThemeManager.h"

@implementation ThemeManager

static ThemeManager *s;

+ (id) sharedThemeManager {
    if (s == nil) {
      s = [[ alloc] init];
    }
    return s;
}

- (id) init {
    if (self = ) {
      self.name = ;
    }
    return self;
}

- (NSString *) description {
    return ;
}

- (void) dealloc {
    ;
    _name = Nil;
    ;
}

@end
main.m
//
//main.m
//ThemeManager
//
//Created by yusian on 14-2-1.
//Copyright (c) 2014年 yusian. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "ThemeManager.h"

int main(int argc, const char * argv[])
{

    @autoreleasepool {
      
      ThemeManager * tm = ;
      
      ThemeManager * tm2 = ;
                        
      NSLog(@"tm is %@",tm);
      NSLog(@"tm2 is %@",tm2);
      
      NSLog(@"tm address is%p, tm2 address is %p",tm,tm2);
    }
    return 0;
}

运行结果:
2014-02-01 21:40:05.406 ThemeManager tm is My name is Default
2014-02-01 21:40:05.408 ThemeManager tm2 is My name is Default
2014-02-01 21:40:05.408 ThemeManager tm address is0x100301c00, tm2 address is 0x100301c00
Program ended with exit code: 0

Sian 发表于 2014-2-1 22:01:50

典型的单例的写法:
+ (id) sharedThemeManager {
      if (s == nil) {
            s = [[ alloc] init];
      }
    return s;
}
加锁的写法:
+ (id) sharedThemeManager {    @synchronized(self){    if (s == nil) {      s = [[ alloc] init];    }    }    return s;}
GCD的写法:+ (id) sharedThemeManager {    static dispatch_once_t onceToken;    dispatch_once(&onceToken, ^{    if (s == nil) {      s = [[ alloc] init];    }    });    return s;}


Sian 发表于 2014-2-2 11:26:30

重载的几个方法写法:
+ (id) copyWithZone: (NSZone *)zone {    return self;}
- (id) retain {    return self;}
- (oneway void) release {
}
- (NSUInteger) retainCount {    return UINT_MAX;}
- (id) autorelease {    return self;}
页: [1]
查看完整版本: 第二十七讲:Objective-C设计模式之单例