各种单例模式

单例模式是一种重要的设计模式

饿汉式:

class Singleton1{
    private Singleton1(){};
    private static Singleton1 singleton1 = new Singleton1();
    public static Singleton1 getInstance(){
        return singleton1;
    }
}

懒汉式一(线程不安全)延迟加载

class Singleton2{
    private Singleton2(){};
    private static Singleton2 singleton2 = null;
    public static Singleton2 getInstance(){
        if(singleton2==null){
            singleton2 = new Singleton2();
        }
        return singleton2;
    }
}

懒汉式二(线程安全低效)

加入synchronized实现同步

class Singleton3{
    private Singleton3(){};
    private static Singleton3 singleton3 = null;
    public static Singleton3 getInstance(){
        synchronized (Singleton3.class){
            if (singleton3 == null){
                singleton3 = new Singleton3();
            }
        }
        return singleton3;
    }
}

懒汉式三(线程安全,高效双重检查锁)

synchronized加双重校检,效率高

class Singleton4{
    private Singleton4() {};
    private volatile static Singleton4 singleton4 = null;
    public static Singleton4 getInstance(){
        if(singleton4 == null){
            synchronized (Singleton4.class){
                if(singleton4 == null){
                    singleton4 = new Singleton4();
                }
            }
        }
        return singleton4;
    }
}

静态内部类式

class Singleton5{
    private Singleton5(){};
    static class Singleton5Holder{
        private static Singleton5 singleton5 = new Singleton5();
    }
    public static Singleton5 getInstance(){
        return Singleton5Holder.singleton5;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_42862882/article/details/89091073