【剑指offer】【面试题2 实现Singleton 模式—七种实现方式】

《剑指Offer》总目录


一、名词解释

单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个对象被创建。这个类提供了一种访问其唯一的对象的方式,可以直接访问,不需要实例化该类的对象。

注意:

  • 1、单例类只能有一个实例。
  • 2、单例类必须自己创建自己的唯一实例。
  • 3、单例类必须给所有其他对象提供这一实例。

二、单例模式的几种实现方式

懒汉式与饿汉式的根本区别在与是否在类内方法外创建自己的对象。并且声明对象都需要私有化,构造方法都要私有化,这样外部才不能通过 new 对象的方式来访问。饿汉式的话是声明并创建对象(因为他饿),懒汉式的话只是声明对象,在调用该类的 getInstance() 方法时才会进行 new 对象。

  1、懒汉式,线程不安全 

  描述:这种方式是最基本的实现方式,这种实现最大的问题就是不支持多线程。因为没有加锁 synchronized,所以严格意义上它并不算单例模式。这种方式 lazy loading 很明显,不要求线程安全,在多线程不能正常工作。

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

2、懒汉式,线程安全

          描述:这种方式具备很好的 lazy loading,能够在多线程中很好的工作,但是,效率很低,99% 情况下不需要同步。
         优点:第一次调用才初始化,避免内存浪费。
         缺点:必须加锁 synchronized 才能保证单例,但加锁会影响效率。getInstance() 的性能对应用程序不是很关键(该方法使用不太频繁)。

public static class Singleton03{
		private static Singleton03 instance= null;
		
		private Singleton03() {
			
		}
		
		public static synchronized  Singleton03 getInstance() {
			if(singLeton == null) {
				instance= new Singleton03();
			}
			return instance;
		}
	}

3、饿汉式,线程安全

描述:这种方式比较常用,但容易产生垃圾对象。
           优点:没有加锁,执行效率会提高。
           缺点:类加载时就初始化,浪费内存。
           它基于 classloader 机制避免了多线程的同步问题,不过,instance 在类装载时就实例化,虽然导致类装载的原因有很多种,在单例模式中大多数都是调用 getInstance 方法, 但是也不能确定有其他的方式(或者其他的静态方法)导致类装载,这时候初始化 instance 显然没有达到 lazy loading 的效果。

public static class Singleton01{
		private static final Singleton01 INSTACNE= new Singleton01();
		
		private Singleton01() {
			
		}
		
		public static  Singleton01 getInstance() {
			return INSTACNE;
		}
	}

4、双检锁/双重校验锁(DCL,即 double-checked locking)JDK1.5 起,懒汉式,线程安全

描述:这种方式采用双锁机制,安全且在多线程情况下能保持高性能。getInstance() 的性能对应用程序很关键。

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

5、静态内部类,懒汉式,线程安全

描述:这种方式能达到双检锁方式一样的功效,但实现更简单。对静态域使用延迟初始化,应使用这种方式而不是双检锁方式。这种方式只适用于静态域的情况,双检锁方式可在实例域需要延迟初始化时使用。
          这种方式同样利用了 classloader 机制来保证初始化 instance 时只有一个线程,它跟第 3 种方式不同的是:第 3 种方式只要 Singleton 类被装载了,那么 instance 就会被实例化(没有达到 lazy loading 效果),而这种方式是 Singleton 类被装载了,instance 不一定被初始化。因为 SingletonHolder 类没有被主动使用,只有通过显式调用 getInstance 方法时,才会显式装载 SingletonHolder 类,从而实例化 instance。想象一下,如果实例化 instance 很消耗资源,所以想让它延迟加载,另外一方面,又不希望在 Singleton 类加载时就实例化,因为不能确保 Singleton 类还可能在其他的地方被主动使用从而被加载,那么这个时候实例化 instance 显然是不合适的。这个时候,这种方式相比第 3 种方式就显得很合理。

public static class Singleton05{
		private static final class SingletonHold{
			private static final Singleton05 INSTANCE= new Singleton05();
		}
		private Singleton05() {
			
		}
		
		public static Singleton05 getInstance() {
			return SingletonHold.INSTANCE;
		}
	}

6、枚举,饿汉式,线程安全    JDK1.5后

描述:这种实现方式还没有被广泛采用,但这是实现单例模式的最佳方法。它更简洁,自动支持序列化机制,绝对防止多次实例化。
           这种方式是 Effective Java 作者 Josh Bloch 提倡的方式,它不仅能避免多线程同步问题,而且还自动支持序列化机制,防止反序列化重新创建新的对象,绝对防止多次实例化。不过,由于 JDK1.5 之后才加入 enum 特性,用这种方式写不免让人感觉生疏,在实际工作中,也很少用。不能通过 reflection attack 来调用私有构造方法。

	public enum Singleton06{
		INSTANCE;
		
		public void whateverMethod() {
			
		}
	}

7、静态块,饿汉式

描述:创建一个类变量后 , 在静态块中将其实例化。由于静态代码块在使用类之前已经执行,可以利用这个特性实现单例模式。前面的方式三是利用静态变量在创建单实例。

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

三、代码测试

package com.acm.firstmonth;

import com.acm.firstmonth.SingLeton.Singleton01;
import com.acm.firstmonth.SingLeton.Singleton02;
import com.acm.firstmonth.SingLeton.Singleton03;
import com.acm.firstmonth.SingLeton.Singleton04;
import com.acm.firstmonth.SingLeton.Singleton05;
import com.acm.firstmonth.SingLeton.Singleton06;
import com.acm.firstmonth.SingLeton.Singleton07;

public class Test02 {
	/**
	 * 饿汉式 线程安全  
	 * @author zc
	 *
	 */
	public static class Singleton01{
		private static final Singleton01 INSTANCE = new Singleton01();
		
		private Singleton01() {}
		
		public static Singleton01 getInstance() {
			return INSTANCE;
		}
	}
	/**
	 * 饿汉式 线程安全
	 * @author zc
	 *
	 */
	public static class Singleton02{
		private static Singleton02 instance ;
		static {
			instance = new Singleton02();
		}
		
		private Singleton02() {}
		
		public static Singleton02 getInstance() {
			return instance;
		}
	}
	/**
	 * 饿汉式  线程安全  JDK1.5+
	 * @author zc
	 *
	 */
	public enum Singleton03{
		INSTANCE;
		
		public void whateverMethod() {}
	}
	/**
	 * 懒汉式 线程不安全
	 * @author zc
	 *
	 */
	public static class Singleton04{
		private static Singleton04 instance = null;
		
		private Singleton04() {}
		
		
		public static Singleton04 getInstance() {
			if(instance == null) {
				return instance = new Singleton04();
			}
			return instance;
		}
	}
	/**
	 * 懒汉式 线程安全
	 * @author zc
	 *
	 */
	public static class Singleton05{
		private static Singleton05 instance = null;
		
		private Singleton05() {}
		
		public static synchronized Singleton05 getInstance() {
			if(instance == null) {
				instance = new Singleton05();
			}
			return instance;
		}
	}
	/**
	 * 静态内部类 线程安全  懒汉式
	 * @author zc
	 *
	 */
	public static class Singleton06{
		
		private static class SingletonHold{
			private static final Singleton06 INSTANCE = new Singleton06();
		}
		
		private Singleton06() {}
		
		public static Singleton06 getInstance() {
			return SingletonHold.INSTANCE;
		}
	}
	/**
	 * 二重锁 懒汉式 线程安全
	 * @author zc
	 *
	 */
	public static class Singleton07{
		private volatile static  Singleton07 instance = null;
		
		private Singleton07() {}
		
		public static Singleton07 getInstance() {
			if(instance == null) {
				synchronized(Singleton07.class) {
					if(instance == null) {
						instance = new Singleton07();
					}
				}
			}
			return instance;
		}
	}
	
	public static void main(String[] args) {
		//饿汉式
		System.out.println( Singleton01.getInstance() == Singleton01.getInstance());
		System.out.println( Singleton02.getInstance() == Singleton02.getInstance());
		System.out.println( (Singleton03.INSTANCE == Singleton03.INSTANCE));
		//懒汉式
		System.out.println( Singleton04.getInstance() == Singleton04.getInstance());
		System.out.println( Singleton05.getInstance() == Singleton05.getInstance());
		System.out.println( Singleton06.getInstance() == Singleton06.getInstance());
		System.out.println( Singleton07.getInstance() == Singleton07.getInstance());
		
	}
	
}
发布了14 篇原创文章 · 获赞 1 · 访问量 5526

猜你喜欢

转载自blog.csdn.net/Vpn_zc/article/details/84100878