设计模式系列3-单例模式
前言:
前一节讲了为什么要用设计模式,这节讲23种设计模式之单例模式。
什么是单例模式?
单例模式:保证一个类仅有一个实例,并提供一个访问它的全局访问点。(最初的定义出现于《设计模式》(Addison-Wesley, 1994)).
单例模式几乎是设计模式最简单的形式了,这一模式的意图使得类的一个实例对象成为系统中的唯一实例。
何时使用单例模式?
在以下情形,应该考虑使用单例模式:
1. 类只能有一个实例,而且必须从一个为人熟知的访问点对其进行访问,比如工厂方法;
2. 这个唯一的实例只能通过子类进行扩展,而且扩展的对象不会破坏客户端源代码。
单例模式在Java中的实现:
1. 饿汉式单例
public class Singleton {
private Singleton() {
}
private static Singleton instance = new Singleton();
public static Singleton getInstance() {
return instance;
}
}
2. 双检索式写法
public class Singleton {
private Singleton() { //构造方法私有
}
private static Singleton instance; //声明静态的单例对象变量
public static Singleton getInstace() { //外部通过此方法获取对象
if (instance == null) {
synchronized (Singleton.class) { //同时只能有一外部线程调用此方法
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
3. Android中用到的单例模式:
Application SharedPreferences等等,在学习的过程中多留意就会发现很多意想不到的收获
单例模式在objective-c中的实现:
1. IOS5+,GCD实现
#import <Foundation/Foundation.h>
@interface MYSingleton : NSObject
+ (MYSingleton *)sharedSingleton;
@end
#import "MYSingleton.h"
@implementation MYSingleton
+ (MYSingleton *)sharedSingleton {
static MYSingleton *instance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[self alloc] initialize];
});
return instance;
}
- (id)initialize {
if (self == [super init]) {
//初始化工作
}
return self;
}
@end
2. IOS5-,实现方法如下:
#import <Foundation/Foundation.h>
@interface MYSingleton : NSObject
+ (MYSingleton *)sharedSingleton;
@end
#import "MYSingleton.h"
static MYSingleton *instance;
@implementation MYSingleton
+ (MYSingleton *)sharedSingleton {
if (!instance) {
@synchronized(self) { //防止多线程同时访问
if (!instance) {
instance = [[self alloc] init]; //该方法会调用 allocWithZone
}
}
}
return instance;
}
+ (id)allocWithZone:(NSZone *)zone {
if (!instance) {
@synchronized(self) {
if (!instance) {
instance = [super allocWithZone:zone];//确保使用同一块内存地址
}
}
}
return instance;
}
- (id)copyWithZone:(NSZone *)zone {
return self; //确保copy对象也是唯一
}
- (id)retain {
return self; //确保计数唯一
}
- (oneway void)release {
//重写计数释放方法
}
@end
2. IOS5-,实现方法如下:
#import <Foundation/Foundation.h>
@interface MYSingleton : NSObject
+ (MYSingleton *)sharedSingleton;
@end
#import "MYSingleton.h"
static MYSingleton *instance;
@implementation MYSingleton
+ (MYSingleton *)sharedSingleton {
if (!instance) {
@synchronized(self) { //防止多线程同时访问
if (!instance) {
instance = [[self alloc] init]; //该方法会调用 allocWithZone
}
}
}
return instance;
}
+ (id)allocWithZone:(NSZone *)zone {
if (!instance) {
@synchronized(self) {
if (!instance) {
instance = [super allocWithZone:zone];//确保使用同一块内存地址
}
}
}
return instance;
}
- (id)copyWithZone:(NSZone *)zone {
return self; //确保copy对象也是唯一
}
- (id)retain {
return self; //确保计数唯一
}
- (oneway void)release {
//重写计数释放方法
}
@end
3. IOS中用到的单例模式:
UIApplication NSNotificationCenter等等