设计模式系列3-单例模式

设计模式系列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  
3. IOS中用到的单例模式:
    UIApplication NSNotificationCenter等等
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值