首页 > 代码库 > 设计模式之——单例模式

设计模式之——单例模式

        单例模式是设计模式中比较简单的一种模式,也是使用的比较多的一种模式。

        特别是在某些对象只需要一个时,比如线程池、缓存、日志对象、注册表对象等。

        如果创建了多个,可能会导致很多问题。比如程序行为异常、资源使用过量等。

         

        单例模式确保程序中一个类最多只有一个实例。

        单例模式提供访问这个实例的全局点。

        在JAVA中单例模式需要:私有构造器、一个静态方法、一个静态变量。

        如果使用多个类加载器,可能会导致单例失效而产生多个实例。

    

        单例模式确保一个类只有一个实例,并提供一个全局的访问点。

        下面为延迟加载的单例模式:

	public class Singleton {
		private static Singleton uniqueInstance;
		
		private Singleton() {}
		
		public static Singleton getInstance() {
			if (uniqueInstance == null) {
				uniqueInstance = new Singleton();
			}
			return uniqueInstance;
		}
	}


处理多线程:需要将getInstance()变成同步(Synchronized),多线程的问题机会就可以轻松解决。

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

       如果应用程序总是创建并使用单例模式、或者在创建和运行时负担不太繁重,可能急切创建实例:

	public class Singleton {
		private static Singleton uniqueInstance = new Singleton();
		
		private Singleton() {}
		
		public static synchronized Singleton getInstance() {
			return uniqueInstance;
		}
	}

使用“双重检查加锁”,在getInstance()中减少使用同步:

        /**
	 * volatile 关键字确保当uniqueInstance变量被初始化
	 * 成Singleton实例时,多个线程正确地处理uniqueInstance变量
	 *
	 */
	public class Singleton {
		private volatile static Singleton uniqueInstance = new Singleton();
		
		private Singleton() {}
		
		public static Singleton getInstance() {
			/**检查实例,不存在则进入同步区**/
			if(uniqueInstance == null){
				/**只有第一次才彻底执行下面代码**/
				synchronized (Singleton.class) {
					/**进入区块中,再检查一次,如果仍为null,才创建实例**/
					if(uniqueInstance == null){
						uniqueInstance = new Singleton();
					}
				}
			}
			return uniqueInstance;
		}
	}


设计模式之——单例模式