IOS设计模式之一:单例模式
2012-09-29 14:40
302 查看
单例模式的意思就是只有一个实例。单例模式确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例。这个类称为单例类。
当然,ios 5以上启用ARC就简单多了:
#import <Foundation/Foundation.h> @interface Singleton : NSObject +(Singleton *) instance; @end @implementation Singleton +(Singleton *) instance { static Singleton *sharedSingleton_ = nil; @synchronized(self){ if(sharedSingleton_ == nil){ sharedSingleton_ = [NSAllocateObject([self class], 0, NULL) init]; } } return sharedSingleton_; } + (id) allocWithZone:(NSZone *)zone { return [[self sharedInstance] retain]; } - (id) copyWithZone:(NSZone*)zone { return self; } - (id) retain { return self; } - (NSUInteger) retainCount { return NSUIntegerMax; } -(void)release { [super release]; } - (id) autorelease { return self; } @end
当然,ios 5以上启用ARC就简单多了:
static RootViewController* sharedRootController = nil; +(RootViewController *) sharedController{ @synchronized(self){ if (sharedRootController == nil) { sharedRootController = [[self alloc] init]; } } return singleController; }
相关文章推荐
- iOS设计模式-策略模式
- ios单态(singleton)设计模式
- ios 开发 设计模式之---策略模式
- iOS设计模式之单例模式
- iOS设计模式(一) 原型模式
- IOS设计模式-组合设计模式
- iOS设计模式之二(门面模式,装饰器模式)
- iOS的集中设计模式
- iOS设计模式 —— KVC
- IOS设计模式第五篇之装饰设计模式的代理设计模式
- IOS开发中常用的设计模式
- iOS 设计模式
- iOS学习笔记-112.多线程11——单例设计模式
- IOS常用的类 函数 COCOA 设计模式
- IOS设计模式之三:MVC模式
- iOS开发设计模式
- iOS开发——设计模式那点事
- 经典设计模式-iOS的实现
- iOS的Objective-C的工厂设计模式详解