单例模式两种实现方式

饿汉模式:
不管调不调用,在类中都实例化好了类的对象。
所以加载类时 速度较慢, 运行时速度较快。线程安全

public class Singleton {
    //1.私有构造函数,不允许外部访问
    private Singleton() {
        super();
        // TODO Auto-generated constructor stub
    }
    //2.创建类的惟一实例,私有。 (类变量)
    private static Singleton instance = new Singleton();
    //3.提供访问惟一实例的公共方法(类方法)
    public static Singleton getInstance(){
        return instance;
    }
}

懒汉模式
只有当真正需要使用类对象时,才去实例化该类的对象。
加载类时速度较快,运行时速度较慢。 线程不安全

public class Singleton2 {
    //1.私有构造函数,不允许外部访问
    private Singleton2() {
        super();
        // TODO Auto-generated constructor stub
    }
    //2.创建类的惟一实例,私有。 (类变量)
    private static Singleton2 instance;
    //3.提供访问惟一实例的公共方法(类方法)
    public static Singleton2 getInstance(){
        if(instance == null){
            instance = new Singleton2();
        }
        return instance;
    }
}

加锁:

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

你可能感兴趣的:(java后台开发学习)