iOS App开发中使用设计模式中的单例模式的实例解析

2025-05-29 0 76

一、单例的作用
顾名思义,单例,即是在整个项目中,这个类的对象只能被初始化一次。它的这种特性,可以广泛应用于某些需要全局共享的资源中,比如管理类,引擎类,也可以通过单例来实现传值。UIApplication、NSUserDefaults等都是IOS中的系统单例。

二、单例模式的两种写法
1,常用写法

?

1

2

3

4

5

6

7

8

9

10

11

12

13
#import "LGManagerCenter.h"

static LGManagerCenter *managerCenter;

@implementation LGManagerCenter

+(LGManagerCenter *)sharedManager{

if(!managerCenter)

managerCenter=[[self allocWithZone:NULL] init];

return managerCenter;

}

@end

2,用GCD创建单例类

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16
#import "LGManagerCenter.h"

@implementation LGManagerCenter

+(LGManagerCenter *)sharedManager{

static dispatch_once_t predicate;

static LGManagerCenter * managerCenter;

dispatch_once(&predicate, ^{

managerCenter=[[LGManagerCenter alloc] init];

});

return managerCenter;

}

@end

其中dispatch_once函数只执行一次。

三、代码的优化
通过上面的方法,我们已经可以使用类方法来得到这个单例,但很多时候,项目的工程量很大,还有可能会很多开发者同时参与一个项目的开发,为了安全与管理代码的方便,也为了给不是这个单例的创作者但会用到这个单例的开发人员一些提示,我们通常会重写一些方法:

首先我们自己实现一个alloc方法:

?

1

2

3
+(instancetype)myAlloc{

return [super allocWithZone:nil];

}

将我们的单例实现方法略作修改:

?

1

2

3

4

5

6

7
+(ZYHPayManager *)sharedMamager{

static ZYHPayManager * manager;

if (manager==nil) {

manager=[[ZYHPayManager myAlloc]init];

}

return manager;

}

将一些视图实例化对象的方法重写:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14
+(instancetype)alloc{

NSAssert(0, @"这是一个单例对象,请使用+(ZYHPayManager *)sharedMamager方法");

return nil;

}

+(instancetype)allocWithZone:(struct _NSZone *)zone{

return [self alloc];

}

-(id)copy{

NSLog(@"这是一个单例对象,copy将不起任何作用");

return self;

}

+(instancetype)new{

return [self alloc];

}

注意:这里的alloc使用了断言,让任何视图通过alloc创建对象的程序段断在此处,给程序员提示。copy方法这里只是简单的返回了原对象,并未做任何处理,打印信息给程序员提示。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 iOS App开发中使用设计模式中的单例模式的实例解析 https://www.kuaiidc.com/93573.html

相关文章

发表评论
暂无评论