设计模式-单例模式

2018-04-15  本文已影响0人  海生2018

单利模式

优势


实现方式

1. 懒汉式

public class Singleton{
    //使用静态实例,防止被引用,赋值null,延迟加载
    private static Singleton instance=null;
    //私有构造方法,防止被实例化
    private Singleton(){}
    //静态工厂方法,创建实例
    public static Singleton getInstance(){
    if(instance==null)
        instance=new Singleton();
    return instance;
}
}

线程安全的懒汉式

public class Singleton{
    private static Singleton instance = null;
    private Singleton(){}
    //在静态工厂方法上加锁
    public static synchronized Singleton getInstance(){
    if(instance == null)
        instance = new Singleton();
    return instance;
}

2. 双检锁/双重校验锁

public class Singleton(){
    //加入volatile禁止指令重排序,且实例在内存中对于其他线程可见
    private volatile static Singleton instance=null;
    private Singleton(){}
    //静态工厂方法中,在第一次创建时加锁
    public static Singleton getInstance(){
        if(instance == null){
            synchronized(Singleton.class){
                if(instance == null){
                    instance=new Singleton();
                }
            }
        }
        return singleton;
    }
}

3. 饿汉式

public class Singleton{
    //声明时赋值
    private static final Singleton instance=new Singleton();
    private Singleton(){}
    public static Singleton getInstance(){
        return instance;
    }
}

4. 静态内部类

public class Singleton{
    private Singleton(){}
    private static class SingletonHolder{
        //准备阶段就赋值
        private static final Singleton instance=new Singleton();
    }
    public static Singleton getInstance(){
        return SingletonHolder.instance;
    }
}

5. 枚举

public enum Singleton{
    INSTANCE;
    public void whateverMethod(){
    }
}
上一篇下一篇

猜你喜欢

热点阅读