1. 单例的概念
单例模式就是一个类只有一个实例,也就是一个对象,它是唯一的。它的生命周期和应用程序绑定。在应用程序结束前,这个实例是共享的。
2. 命名规则
这个规则是习惯性的规则,并不是强制的,一定要这样命名。
一般这样:share + 你的类名 或者 default + 你的类名
3. 单例设计模式的优缺点
主要有点:
1. 提供了对唯一实例的受控访问,可以在不同的窗口进行数据的传递。
2. 由于在系统内存中只存在一个对象,因此可以节约系统资源,对于一些需要频繁创建和销毁的对象单例模式无疑可以提高系统的性能。
主要缺点:
1. 由于单利模式中没有抽象层,因此单例类的扩展有很大的困难
2. 滥用单例将带来一些负面问题,如:为了节省资源将数据库连接池对象设计为单例类,可能会导致共享连接池对象的程序过多而出现连接池溢出;如果实例化的对象长时间不被利用,系统会认为是垃圾而被回收,这将导致对象状态的丢失。
实现过程:
拿国王这个类来创建一个单例类
#import <Foundation/Foundation.h>@interface Kingdom : NSObject < NSCopying >+ ( Kingdom * ) sharedKindom ;@property ( nonatomic , assign ) NSInteger age ;@end
#import "Kingdom.h"@implementation Kingdom// GCD 模式static Kingdom * singleton = nil ;+ ( Kingdom * ) sharedKindom{// onceToken 令牌用来标识,一旦调用,就被设置,作为唯一标示符// dispatch_once 类似一把锁static dispatch_once_t onceToken ;dispatch_once ( & onceToken , ^ {singleton = [[ self alloc ] init ];});return singleton ;}+ ( id ) allocWithZone: ( NSZone * ) zone{static dispatch_once_t onceToken ;NSLog ( @"onceToken : %ld" , onceToken );dispatch_once ( & onceToken , ^ {singleton = [ super allocWithZone : zone ];});return singleton ;}- ( id ) copyWithZone: ( NSZone * ) zone{return self ;}// MRC 环境下/*static Kingdom *singleton = nil;+ (Kingdom *)sharedKindom{@synchronized(self) {if (singleton == nil) {singleton = [[self alloc] init];}}return singleton;}+ (id)allocWithZone:(NSZone *)zone{@synchronized(self) {if (singleton == nil) {singleton = [super allocWithZone:zone];}}return singleton;}- (id)copyWithZone:(NSZone *)zone{return self;}- (oneway void)release{}- (id)autorelease{return self;}- (NSUInteger)retainCount{return INT_MAX;}*/// ARC 环境下/*static Kingdom *singleton = nil;+ (Kingdom *)sharedKindom{@synchronized(self) {if (singleton == nil) {singleton = [[self alloc] init];}}return singleton;}+ (id)allocWithZone:(NSZone *)zone{@synchronized(self) {if (singleton == nil) {singleton = [super allocWithZone:zone];}}return singleton;}- (id)copyWithZone:(NSZone *)zone{return self;}*/@end