单例模式在实际开发中用法也比较简单,一般是获取唯一实例调用其内部的静态方法.这里不多做赘述,主要记录常用的单例模式使用的三种方法
增加: 多线程并发操作,单例模式的正确写法,加入Volatile关键字http://www.race604.com/java-double-checked-singleton/
</br>
单例模式-方法:
1.拥有一个private构造函数,不对外开放
2.通过static静态方法返回单例类对象
3.确保多线程环境下,单例类的对象有且只有一个
</br>
优点:
1.在内存在只有一个实例,减少内存开支
2.避免对资源的多重占用
</br>
缺点:
1.没有缺口,扩展困难
2.单例对象如果持有context,容易引发内存泄露
</br>
考虑线程同步,增加Volatile关键字的单例模式:
private static volatile SettingsDbHelper sInst = null; // <<< 这里添加了 volatile
public static SettingsDbHelper getInstance(Context context) {
SettingsDbHelper inst = sInst; // <<< 在这里创建临时变量
if (inst == null) {
synchronized (SettingsDbHelper.class) {
inst = sInst;
if (inst == null) {
inst = new SettingsDbHelper(context);
sInst = inst;
}
}
}
return inst; // <<< 注意这里返回的是临时变量
}
常用的单例模式代码片段:
static //Double CheckLock(DCL)实现单例
class SingletonTwo{
private static SingletonTwo mInstance = null;
//构造函数私有
private SingletonTwo(){
}
public static SingletonTwo getInstance(){
if (mInstance == null) {
synchronized (SingletonTwo.class) { //之前有次面试,就考用DCL实现单例模式的代码,
if (mInstance == null) {
mInstance = new SingletonTwo();
}
}
}
return mInstance;
}
}
static //懒汉模式
class SingletonThree{
private static SingletonThree mInstance;
//构造函数私有
private SingletonThree(){
}
public static synchronized SingletonThree getInstance(){
if (mInstance == null) {
mInstance = new SingletonThree();
}
return mInstance;
}
}
static //静态内部类实现单例模式
class SingletonFour{
//构造函数私有
private SingletonFour(){
}
public static SingletonFour getInstance(){
return SingletonFourHolder.mInstance;
}
/*
* 静态内部类
*/
private static class SingletonFourHolder{
private static final SingletonFour mInstance = new SingletonFour();
}
}