• [oc学习日记]单例模式


    首先来了解一下单例模式的概念

    单例模式就是保证系统中只存在一个对象(只有一个地址)的模式

    下面我们就由一个学生类举例说明

    因为要保证系统只有一个对象就要重写对象的创建方法,对象的拷贝方法

    1 #import <Foundation/Foundation.h>
    2 //因为要重写拷贝方法,所以要遵循拷贝协议
    3 @interface Student : NSObject<NSCopying,NSMutableCopying>
    4 +(id)create;//声明创建对象的方法
    5 @end

     接下来我们再来看这些方法的实现过程

    注意事项:

    1.一定要先创建一个静态全局的对象(确保只有一个地址的保障)

    2.重写alloc和new的创建方法时,使用类名创建会出错,所以要用super

    3.为防止多线程操作冲突,要用@synchronized进行避免

     1 #import "Student.h"
     2 //首先要创建一个静态全局的对象
     3 static Student *stu = nil;
     4 @implementation Student
     5 +(id)create//实现创建对象的方法
     6 {
     7     @synchronized (self)//防止多线程操作冲突
     8     {
     9         if (stu == nil) {
    10             stu = [[Student alloc]init];//如果对象为空的话,就创建新对象,否则返回,保证只有一个对象
    11         }
    12         return stu;
    13     }
    14 }
    15 //重写alloc和new的创建对象方法
    16 +(instancetype)allocWithZone:(struct _NSZone *)zone
    17 {
    18     @synchronized (self)
    19     {
    20         if (stu == nil) {
    21             stu = [[super allocWithZone:zone]init];//如果对象为空的话,就创建新对象,否则返回,保证只有一个对象
    22         }
    23         return stu;
    24     }
    25 }
    26 //重写浅拷贝方法
    27 -(id)copyWithZone:(NSZone *)zone
    28 {
    29     return stu;
    30 }
    31 //重写深拷贝方法
    32 -(id)mutableCopyWithZone:(NSZone *)zone
    33 {
    34     return stu;
    35 }
    36 @end

     主函数的实现

    我们虽然在主函数中定义了很多student的方法,但是所有对象的空间只有一个

     1 #import <Foundation/Foundation.h>
     2 #import "Student.h"
     3 int main(int argc, const char * argv[]) {
     4     @autoreleasepool {
     5         Student *stu = [[Student alloc]init];
     6         Student *stu1 = [[Student alloc]init];
     7         Student *stu2 = [Student new];
     8         Student *stu3 = [stu copy];
     9         Student *stu4 = [stu mutableCopy];
    10         NSLog(@"
    %@
    %@
    %@
    %@
    %@",stu,stu1,stu2,stu3,stu4);
    11     }
    12     return 0;
    13 }

    主函数的运行效果

    2015-06-05 09:17:48.274 day26_01[643:12774] 
    <Student: 0x100304460>
    <Student: 0x100304460>
    <Student: 0x100304460>
    <Student: 0x100304460>
    <Student: 0x100304460>
  • 相关阅读:
    union和union all 合并查询
    c#中取整,向上取,向下取
    多个DataSet数据合并
    js未定义判断
    C# 获取时间差状态
    SQL中inner join、outer join和cross join的区别
    朗朗跄跄的受伤,跌跌撞撞的坚强
    IIS7.5 平台.NET无后缀名伪静态实现办法-服务器配置
    检查Android系统版本
    js 实现搜索功能
  • 原文地址:https://www.cnblogs.com/0error/p/4553806.html
Copyright © 2020-2023  润新知