OC--单例模式

话不多说,同样是个人笔记。

1、在头文件声明类方法
#import <Foundation/Foundation.h>

@interface Student : NSObject
+ (Student*) getInstance;
@end

2、在源文件中实现相应方法

#import "Student.h"

static Student* instance = nil;

@interface Student()
- (instancetype) init;
@end

@implementation Student
+ (Student*) getInstance {
    if (instance == nil) {
        instance = [[Student alloc]init];
    }

    return instance;
}

- (instancetype) init {
    return self;
}

//覆盖allocWithZone
+ (id) allocWithZone:(struct _NSZone *)zone {
    @synchronized(self) {
        if (!instance) {
            instance = [super allocWithZone:zone];//确保使用同一块内存地址
            return instance;
        }
    }

    return nil;
}

- (id) copyWithZone: (NSZone*)zone {
    return self;//确保copy对象也是唯一
}
@end

3、调用

Student* stu1 = [Student getInstance];
Student* stu2 = [Student getInstance];
Student* stu3 = [stu1 copy];
    
NSLog(@"stu1 = %@", stu1);
NSLog(@"stu2 = %@", stu2);
NSLog(@"stu3 = %@", stu3);

4、测试结果

stu1 = <Student: 0x100503920>
stu2 = <Student: 0x100503920>
stu3 = <Student: 0x100503920>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 导读: 一、什么是单例模式 二、单例的作用 三、常见的单例类 四、自定义单例类的方法 一、什么是单例模式 单例模式...
    千山小畻阅读 5,098评论 0 0
  • 版权声明:本文为博主原创文章,未经博主允许不得转载。 单例模式的意思就是只有一个实例。单例模式确保某一个类只有一个...
    LeaderBiao阅读 4,594评论 0 1
  • 单例是在我们在项目学习特别是在工具类的抽取中经常用到的一种设计模式。说道底,单例就是一个类唯一的实例对象,我们无法...
    木子尚武阅读 4,758评论 0 1
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,771评论 19 139
  • 回想这两天的奔波,虽然不易,但事情总归告一段落,那些擦肩而过的人,依然回到自己的生活轨道上,就像我一样回到大山里。...
    止于丘隅阅读 3,068评论 0 0