设计模式-单例模式

- 懒汉模式(线程不安全)
满足懒加载,但是线程不安全,不满足单例的需求。

public class Singleton01 {
     
    public String value;
    private static Singleton01 instance;
    private Singleton01(String value){
     
        try{
     
            Thread.sleep(1000);
        } catch (InterruptedException e) {
     
            e.printStackTrace();
        }
        this.value = value;
    }
    public static Singleton01 getInstance(String value){
     
        if(instance==null){
     
            instance = new Singleton01(value);
            return instance;
        }
        return instance;

    }
}
public class Demo01 {
     
    public static void main(String[] args) {
     
        Singleton01 singleton01 = Singleton01.getInstance("FGNB");
        Singleton01 anotherSingleton01 = Singleton01.getInstance("FGSB");
        System.out.println(singleton01.value);
        System.out.println(anotherSingleton01.value);
    }
}

结果:

FGNB
FGNB

- 懒汉模式(线程安全)
满足懒加载,并且线程安全,但是synchronized加在方法上会浪费资源,所以也不这样用。

public class Singleton02 {
     
    private static Singleton02 instance;
    public String value;
    private Singleton02(String value){
     
        this.value = value;
    }
    public static synchronized Singleton02 getInstance(String value){
     
        if(instance != null){
     
            return instance;
        }
        instance = new Singleton02(value);
        return instance;
    }
}

- 饿汉模式(线程安全)
不满足懒加载。

public class Singleton03 {
     
    public String value;
    private static Singleton03 instance = new Singleton03();

    private Singleton03(){
     
    }

    public static Singleton03 getInstance(String value){
     
        instance.value = value;
        return instance;
    }
}
  • . 使⽤类的内部类(线程安全)
    满足懒加载,并且线程安全,推荐使用。
public class Singleton04 {
     
    private Singleton04(){
     }
    public String value;
    private static class SingletonHolder{
     
        private static Singleton04 instance = new Singleton04();
    }
    public static Singleton04 getInstance(String value){
     
        SingletonHolder.instance.value = value;
        return SingletonHolder.instance;
    }
}
  • 双重锁校验(线程安全)
    对懒汉模式的优化,推荐使用。
public class Singleton05 {
     
    private static Singleton05 instance;

    private String value;
    
    private Singleton05(String value){
     
        this.value = value;
    }
    public static Singleton05 getInstance(String value){
     
        if(null!=instance) return instance;
        synchronized(Singleton05.class){
     
            if(null == instance){
     
                instance = new Singleton05(value);
            }
        }
        return instance;
    }
}
  • Effective Java作者推荐的枚举单例(线程安全)
    存在继承情况下不可用,其他情况还是挺推荐使用的。
public enum Singleton07 {
     
    INSTANCE;
    public void test(){
     
        System.out.println("hi~");
    }
}

你可能感兴趣的:(java设计模式,设计模式)