单例模式

来源:互联网 发布:php sendmail 发邮件 编辑:程序博客网 时间:2024/06/05 14:39

单例模式一般用于某一个类只能有一个实例时。例如一些硬件资源,或者只需要有一个实例就可以的类。这个时候我们就需要利用单例模式去处理。

  • [UIApplication sharedAPplication]
  • [NSBundle mainBunle]
  • [NSFileManager defaultManager]
  • [NSNotificationCenter defaultCenter]
  • [NSUserDefaults defaultUserDefaults]

单例模式的创建

//Singleton.h@interface Singleton : NSObject+ (Singleton *)sharedSingleton;@end//Singleton.m#import "Singleton.h"@implementation Singleton   static Singleton *sharedSingleton = nil;+ (Singleton *)sharedSingleton{    static dispatch_once_t once;    dispatch_once(&once,^{        if(sharedSingleton == nil) {            sharedSingleton = [[super alllocWithZone:NULL] init];            else {                NSLog(@"已经存在");            }        }    });    return sharedSingleton;}
  • 这里用一个静态变量是为了确保它在类中的全局可用性
  • 利用dispatch_once是为了保证初始化代码只执行一次

为了贯彻单例的思想,需要重写的一些方法

+ (id)allocWithZone:(NSZone *)zone {        return [[MySingletonClass sharedSingleton] retain];}- (id)copyWithZone:(NSZone *)zone {        return self;}- (id)retain {        return self;}- (id)autorelease {        return self;}- (void)release {}- (NSUInteger)retainCount {        return NSUIntegerMax;}

单例模式的应用:

假如我们需要在iOS应用中实现分层的架构设计,即我们需要把数据的持久层,展示层,和逻辑层分开。为了突出重点,我们直接把目光转到持久层,而根据MVC的设计模式,我们又可以把持久层细分为DAO层(放置访问数据对象的四类方法)和Domain层(各种实体类,比如学生),这样就可以使用DAO层中的方法,配合实体类Domain层对数据进行清晰的增删改查。那么我们如何设计呢?

从使用者的角度看,我们期望获得DAO层的类实例,然后调用它的增删改查四大方法。可是这个类实例,我们似乎只需要一个就足够了,再多的话不利于管理且浪费内存。OK,我们可以使用单例模式了,代码如下:
.h文件:

//StudentDAO.h@interface StudentDAO:NSObject@property (nonatomic,strong) NSMutaleArray *StudentsInfo;+ (StudentDAO *)sharedStudentDAO;-(int) create:(Student*)student;-(int) remove:(Student*)student;-(int) modify:(Student*)student;-(NSMutaleArray) findAll;@end

.m

//StudentDAO.m#import "StudentDAO.h"#import "Student.h"@implementation StudentDAOstatic StudentDAO *studentDao = nil;+ (StudentDAO)sharedStudentDAO{    static dispatch_once_t once;    dispatch_once(&once,^{        Student  *student1 = [[Student alloc]init];        student1.name = "MexiQQ";        student1.studentNum = "201200301101";        Student  *student2 = [[Student alloc]init];        student2.name = "Ricardo_LI";        student2.studentNum = "201200301102";        studentDao = [[self alloc] init];        studentDao._StudentsInfo = [[NSMutaleArray alloc]init];        [studentDao._StudentsInfo addObject:student1];        [studentDao._StudentsInfo addObject:student2];    });    return studentDao;}   //插入的方法-(int)create:(Student*)stu{    [self._StudentsInfo addObject:stu];    return 0;}   //删除的方法-(int)remove:(Student*)stu{    for(Student* s in self._StudentsInfo){        if([stu.studentNum isEqual:s.studentNum]){            [self._StudentsInfo removeObject:s]            break;        }    }}-(int)modify...... //省略不写-(NSMutaleArray)findAll...... //省略不写

参考文章:https://segmentfault.com/a/1190000000768605

0 0
原创粉丝点击