设计模式-单例模式

为什么需要单例模式?

  1. 某个类在系统中的实例只需要一个就可以,重复初始化浪费资源。
  2. 系统只需要一个实例对象,要求是全局唯一的。
  3. 类的初始化资源消耗太大而只允许创建一个对象。

实现方式

懒汉式:

在第一次获取该实例时才创建,好处:节省资源。缺点:需要考虑多线程环境下的线程安全问题,可能会导致多次重复创建。需要加锁避免这种情况。

public LazySingLeton{

	// volatile 使其他线程更快速的观察到变化
	private volatile static LaztSingleton singleton = null;
  
	// 私有化构造方法,无法通过new来创建实例  
	private LazySingleton(){
    }

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

}

饿汉式:

在类初始化时就创建好实例,实现简单。缺点:有可能系统一直没用到该实例,造成资源的浪费。

public class EagerSingleton{
	private static final EagerSingleton singleton = new EagerSingleton();
  
	private EagerSingleton(){
    }
  
	public static EagerSingleton getInstance(){
    	return singleton;
    }
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务