设计模式之单例

//饿汉式 不推荐
public class Singleton{
    private static final  Singleton singleton = new Singleton();
    public static Singleton getInstance(){
        return singleton;
    }
}


//懒汉式 不推荐
public class Singleton{
    private static Singleton singleton;
    private Singleton(){
        
    }
    public static  sysnchronized  Singleton getInstance(){
        if(null==instance){
            instance = new Singleton();
        }
        return instance;
    }
}
//双重检查锁定(DCL) 不推荐懒汉式的优化版
public class Singleton{
    private static Singleton instance = null;
    private Singleton(){
        
    }
    public static Singleton getInstance(){
        if(null == instance){
            synchronized(Singleton.class){
                if(null==instace){
                    instance = new Singleton
                }
            } 
        }
        return instance;
    }
}

//静态内部单例 推荐
public class Singleton{
    private static Singleton getInstance(){
        return Singletons.singleton;
    }
    
    private static class Singletons{
        private  static final Singleton singleton = new Singleton(); 
    }
}

//枚举单例 推荐
public enum Singleton{
    INSTANCE;
    public void doSomething(){
        System.out.println("操作单例");
    }
}
//使用容器
public class SingletonManager{
    private static Map objMap = new HashMap();
    public static void registerService(String key ,Object instance){
        if(!objMap.containsKey(key)){
            objMap.put(instance);
        }
    }
    public static Object getService(String key){
        return objMap.get(key);
    }
}

具体可参考

你可能感兴趣的:(设计模式之单例)