码迷,mamicode.com
首页 > 其他好文 > 详细

单例设计模式

时间:2017-03-31 23:47:18      阅读:275      评论:0      收藏:0      [点我收藏+]

标签:return   define   oat   stat   size   har   retain   single   type   

1.单例模式概念

  • 什么是单例模式:(Singleton)

    • 单例模式的意图是让类的对象成为系统中唯一的实例。
  • 什么情况下使用单例?

    • 1、类只能有一个实例,而且必须从一个为人熟知的访问点对其进行访问,比如工厂方 法。
    • 2、这个唯一的实例只能通过子类化进行扩展,而且扩展的对象不会破坏客户端代码。
  • 单例设计模式的要点:

    • 1) 某个类只能有一个实例。
    • 2)他必须自行创建这个对象
    • 3)必须自行向整个系统??供这个实例;
    • 4)为了保证实例的唯一性,我们必须将
    • 5)这个方法必须是一个静态类

2.简单的单例模式实现

Singleton.h

// 以后就可以使用interfaceSingleton来替代后面的方法声明
#define interfaceSingleton(name)  +(instancetype)share##name


#if __has_feature(objc_arc)
// ARC
#define implementationSingleton(name)  + (instancetype)share##name { name *instance = [[self alloc] init]; return instance; } static name *_instance = nil; + (instancetype)allocWithZone:(struct _NSZone *)zone { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instance = [[super allocWithZone:zone] init]; }); return _instance; } - (id)copyWithZone:(NSZone *)zone{ return _instance; } - (id)mutableCopyWithZone:(NSZone *)zone { return _instance; }
#else
// MRC

#define implementationSingleton(name)  + (instancetype)share##name { name *instance = [[self alloc] init]; return instance; } static name *_instance = nil; + (instancetype)allocWithZone:(struct _NSZone *)zone { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _instance = [[super allocWithZone:zone] init]; }); return _instance; } - (id)copyWithZone:(NSZone *)zone{ return _instance; } - (id)mutableCopyWithZone:(NSZone *)zone { return _instance; } - (oneway void)release { } - (instancetype)retain { return _instance; } - (NSUInteger)retainCount { return  MAXFLOAT; }
#endif
//
//  Person.h


#import <Foundation/Foundation.h>
#import "Singleton.h"

@interface Person : NSObject

interfaceSingleton(Person);

@end
//
//  Person.m



#import "Person.h"

@implementation Person


implementationSingleton(Person)

@end

 

单例设计模式

标签:return   define   oat   stat   size   har   retain   single   type   

原文地址:http://www.cnblogs.com/xufengyuan/p/6653758.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!