设计模式系列3-单例模式
前言:
什么是单例模式?
何时使用单例模式?
单例模式在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中用到的单例模式:
1518



被折叠的 条评论
为什么被折叠?



