单例模式

  创建型模式

  单例模式:在程序运行过程中采用该模式的类只有一个对象实例,

  要实现该结果要保证私有化构造器,使其只能在类的内部生成实例对象;同时还要提供给外部获取该实例的方法,该实例只能是同一个,所以需要加static关键字;方法返回该实例对象,所以该方法也需要是静态方法。

实现一:饿汉式

  优点:线程安全

  缺点:实例加载时间长(该实例在类加载开始就加载在内存中,直到类的生命周期结束)

class HungryBoy{
	private HungryBoy(){}
	
	private static HungryBoy instance = new HungryBoy();
	
	public static HungryBoy getInstance() {
		return instance;
	} 
}

实现二:懒汉式 

  优点:延迟加载实例

  缺点:线程不安全

class LazyBoy{
	private LazyBoy() {}
	
	private static LazyBoy instance= null;
	
	public static LazyBoy getInstance() {
		if(instance != null) {
			instance = new LazyBoy();
		}
		return instance;
	}
	
}

实现三:懒汉式(线程安全版)

public class LazyBoy {

    private LazyBoy(){    }

    private static LazyBoy instance = null;

    public static LazyBoy getInstance() {
        if(instance == null){
            synchronized (LazyBoy.class){		//这样做效率更高
                if(instance == null){
                    instance = new LazyBoy();
                }
            }
        }
        return instance;
    }
}

  

原文地址:https://www.cnblogs.com/MT-1996/p/13027831.html