iOS常用设计模式——单例设计模式 -电脑资料

电脑资料 时间:2019-01-01 我要投稿
【www.unjs.com - 电脑资料】

   

单例设计模式详解

    单例设计模式详解 基本概念 在IOS中使用单例模式的情况 非ARC环境创建单例模式的基本步骤 非ARC环境具体代码实现 ARC环境创建单例模式的基本步骤

基本概念

    单例模式是一种常用的软件设计模式,

iOS常用设计模式——单例设计模式

。在它的核心结构中只包含一个被称为单例类的特殊类。通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问

在IOS中使用单例模式的情况

    1.如果说创建一个对象会耗费很多系统资源,那么此时采用单例模式,因为只需要一个实例,会节省alloc的时间

    2.在IOS开发中,如果很多模块都要使用同一个变量,此时如果把该变量放入单例类,则所有访问该变量的调用变得很容易,否则,只能通过一个模块传递给另外一个模块,这样增加了风险和复杂度

非ARC环境创建单例模式的基本步骤

    1.声明一个单例对象的静态实例,并初始化为nil

    2.声明一个类的工厂方法,生成一个该类的实例,并且只会生成一个

    3.覆盖allcoWithZone方法,确保用户在alloc 时,不会产生一个多余的对象

    4.实现NSCopying协议,覆盖release,autorelease,retain,retainCount方法,以确保只有一个实例化对象

    5.在多线程的环境中,注意使用@synchronized关键字

非ARC环境具体代码实现

<code class="hljs objectivec">#import<foundation foundation.h="">@interface UserContext : NSObject@property (nonatomic,retain) NSString *username;@property(nonatomic,retain)NSString *email;+(id)sharedUserDefault;@end////  UserContext.m//  SingleDemo////  Created by andyyang on 9/30/13.//  Copyright (c) 2013 andyyang. All rights reserved.//#import "UserContext.h"static UserContext *singleInstance=nil;@implementation UserContext+(id)sharedUserDefault{    if(singleInstance==nil)    {        @synchronized(self)        {            if(singleInstance==nil)            {                singleInstance=[[[self class] alloc] init];            }        }    }    return singleInstance;}+ (id)allocWithZone:(NSZone *)zone;{ if(singleInstance==nil){    singleInstance=[super allocWithZone:zone];}    return singleInstance;}-(id)copyWithZone:(NSZone *)zone{    return singleInstance;}-(id)retain{    return singleInstance;}- (oneway void)release{}- (id)autorelease{    return singleInstance;}- (NSUInteger)retainCount{    return UINT_MAX;}@end#import<foundation foundation.h="">#import "UserContext.h"int main(int argc, const char * argv[]){    @autoreleasepool {       UserContext *userContext1=[UserContext sharedUserDefault];        UserContext *userContext2=[UserContext sharedUserDefault];        UserContext *userContext3=[[UserContext alloc] init];        UserContext *userContext4=[userContext1 copy];        // insert code here...        NSLog(@"Hello, World!");    }    return 0;}</foundation></foundation></code>

ARC环境创建单例模式的基本步骤

<code class="hljs objectivec">+ (instantClass *)sharedClient {static instantClass *_sharedClient = nil;static dispatch_once_t onceToken;dispatch_once(&onceToken, ^{_sharedClient = [[instantClass alloc] init];});return _sharedClient;}</code>

    该方法有很多优势:

    1 线程安全

    2 很好满足静态分析器要求

    3 和自动引用计数(ARC)兼容

    4 仅需要少量代码

最新文章