1.单例模式
单例模式是在实际项目开发中用到比较多的一种设计模式,设计原理是整个系统只产生一个对象实例,通过一个统一的方法对外提供这个实例给外部使用。
单例模式实现:
#import <Foundation/Foundation.h> @interface Singleton : NSObject +(instancetype) shareInstance ; @end
#import "Singleton.h" @implementation Singleton static Singleton* _instance = nil; +(instancetype) shareInstance { static dispatch_once_t onceToken ; dispatch_once(&onceToken, ^{ _instance = [[super allocWithZone:NULL] init] ; }) ; //GCD方式实现单次访问 return _instance ; } +(id) allocWithZone:(struct _NSZone *)zone { return [Singleton shareInstance] ; } -(id) copyWithZone:(struct _NSZone *)zone { return [Singleton shareInstance] ; } @end
覆盖allocWithZone:和copyWithZone:方法,防止通过alloc和init以及copy来构造对象。
原文:http://www.cnblogs.com/xiaotiansean/p/5267684.html