1饿汉式(空间换时间)
public class SingletHungry {
private static SingletHungry hungry = new SingletHungry();
private SingletHungry(){}
public static SingletHungry getInstance(){
return hungry;
}
}
2懒汉式(时间换空间)
public class SingletonIdler {
private static SingletonIdler idler = null;
public static SingletonIdler getInstance(){
if(idler == null){
idler = new SingletonIdler();
}
return idler;
}
private SingletonIdler(){}
}
3双重锁式(DCL)
public class Singleton {
private static Singleton singleton = null;
private Singleton(){}
public static Singleton getInstance(){
if(singleton == null){
synchronized (Singleton.class) {
if(singleton == null){
singleton = new Singleton();
}
}
}
return singleton;
}
}
4静态内部类单例模式(建议使用)
public class SingleStaticClass {
private SingleStaticClass() {
}
public static SingleStaticClass getInstance(){
return SingletonHolder.SInstance;
}
private static class SingletonHolder{
private static final SingleStaticClass SInstance = new SingleStaticClass();
}
}
5枚举单例
public enum enumSingle {
INSTANCE;
public void doSomething(){
System.out.println("枚举的单例");
}
}
6容器实现单例(类管理器)
public class SingletonManager {
private static Map<String, Object> objMap = new HashMap<>();
private SingletonManager(){}
public static void registerService(String key,Object value){
if(!objMap.containsKey(key)){
objMap.put(key, value);
}
}
public static Object getService(String key){
return objMap.get(key);
}
}