实现单例模式的两种方式

简单的懒汉饿汉就不谈了~

方式一:使用synchronized的双重锁定

package com.example.demo;

public class Singleton {

    private static Singleton instance;

    private Singleton(){
        System.out.println(instance);
    }

    public static Singleton getInstance(){
        if(instance == null){
            synchronized (Singleton.class){
                if(instance == null){
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

方式二:内部类中new出Singleton的静态对象

既不用加锁,也可以实现懒加载

package com.example.demo;

public class Singleton {

    private Singleton(){
        System.out.println("instance");
    }

    private static class Inner{
        private static Singleton instance = new Singleton();
    }

    public static Singleton getInstance(){
        return Inner.instance;
    }
}

猜你喜欢

转载自blog.csdn.net/Forest24/article/details/89424607
今日推荐