java单例模式就有6种,你知道哪几种?!

来源:互联网 发布:张无忌萧峰 知乎 编辑:程序博客网 时间:2024/06/09 19:11
 第一种: 双重查锁模式
/**
* Author : Akeem
* Email : zuiaisha1@126.com
* Created by Akeem on 2016/3/7.
* double check lock
*/
public class DoubleCheckLock {
private static DoubleCheckLock instance null;


private DoubleCheckLock() {
}


public static DoubleCheckLock getInstance() {
if (instance == null) {
synchronized (DoubleCheckLock.class) {
if (instance == null) {
instance new DoubleCheckLock();
}
}
}
return instance;
}
}

第二种:懒汉模式

/**
* Author : Akeem
* Email : zuiaisha1@126.com
* Description : 懒汉
* Created by Akeem on 2016/3/7.
*/
public class Idler {
private static Idler instance;
private Idler() {

}

public synchronized static Idler getInstance() {
if (instance == null) {
instance new Idler();
}
return instance;
}
}
 
第三种:枚举单例

/**
* Author : Akeem
* Email : zuiaisha1@126.com
* Description :
* Created by Akeem on 2016/3/7.
*/
public enum SingleEnum {

INSTANCE;
public void doSomething() {
ToastUtils.showLongToast("do something...");

}
}

第四种 :静态内部类模式
/**
* Author : Akeem
* Email : zuiaisha1@126.com
* Description : 静态内部类
* Created by Akeem on 2016/3/7.
*/
public class StaticInner {

private static StaticInner instance;
public static StaticInner getInstance() {
return SingletonHolder.STATIC_INNER;
}
private static class SingletonHolder {
private static final StaticInner STATIC_INNER new StaticInner();
}
} 

第五种 第六种 : 恶汉单例,单例管理类   
/**
* Author : Akeem
* Email : zuiaisha1@126.com
* Description : 单例管理类 ,系统就是这么干的
* Created by Akeem on 2016/3/7.
*/
public class SingletonManager {
private static Map<StringObject> objMap new HashMap<>();

private SingletonManager() {

}

public static void registerInstance(String keyObject o) {
if (!objMap.containsKey(key)) {
objMap.put(keyo);
}
}

public static Object getService(String key) {
return objMap.get(key);
}
} 
0 0
原创粉丝点击