OC--单例模式

作者: 就怕是个demo | 来源:发表于2016-02-25 15:58 被阅读50次

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

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>

相关文章

  • OC--单例模式

    话不多说,同样是个人笔记。 1、在头文件声明类方法#import

  • 【设计模式】单例模式

    单例模式 常用单例模式: 懒汉单例模式: 静态内部类单例模式: Android Application 中使用单例模式:

  • Android设计模式总结

    单例模式:饿汉单例模式://饿汉单例模式 懒汉单例模式: Double CheckLock(DCL)实现单例 Bu...

  • 2018-04-08php实战设计模式

    一、单例模式 单例模式是最经典的设计模式之一,到底什么是单例?单例模式适用场景是什么?单例模式如何设计?php中单...

  • 设计模式之单例模式详解

    设计模式之单例模式详解 单例模式写法大全,也许有你不知道的写法 导航 引言 什么是单例? 单例模式作用 单例模式的...

  • Telegram开源项目之单例模式

    NotificationCenter的单例模式 NotificationCenter的单例模式分析 这种单例模式是...

  • 单例模式Java篇

    单例设计模式- 饿汉式 单例设计模式 - 懒汉式 单例设计模式 - 懒汉式 - 多线程并发 单例设计模式 - 懒汉...

  • IOS单例模式的底层原理

    单例介绍 本文源码下载地址 1.什么是单例 说到单例首先要提到单例模式,因为单例模式是单例存在的目的 单例模式是一...

  • 单例

    iOS单例模式iOS之单例模式初探iOS单例详解

  • 单例模式

    单例模式1 单例模式2

网友评论

  • ShawnDu:其实项目中没有写这么多的, oc中一般都是用
    + (AccountManager *)sharedInstance
    {
    static AccountManager *sharedAccountManagerInstance = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
    sharedAccountManagerInstance = [[self alloc] init];
    });
    return sharedAccountManagerInstance;
    }
    swift中,一般就一句话 static let sharedInstance = ConnectManager()
    就怕是个demo:@杜帅帅_shawn 但是还没普及。所以我还得搞OC
    ShawnDu:@疯狂的米老鼠 用swift还可以,比OC简洁多了
    就怕是个demo:@杜帅帅_shawn 谢谢你。我是用swift开发项目。现在反过来看看oc。其实写单例也并不只有一种方式。这个相对好理解些。再次谢谢你😄

本文标题:OC--单例模式

本文链接:https://www.haomeiwen.com/subject/gngikttx.html