Singleton模式的五种实现

单例模式的特点:

  • 单例类只能有一个实例。
  • 单例类必须自己创建自己的唯一实例。
  • 单例类必须给所有其他对象提供这一实例。 -《Java与模式》

单例类可以是没有状态的,仅用做提供工具性函数的对象。既然是提供工具性函数,也就没有必要创建多个实例。

 

下面列举单例模式的几种实现:

  • 单元素的枚举类型实现Singleton – the preferred approach.enum类型是Jdk1.5引入的一种新的数据类型.其背后的基本想法:通过公有的静态final域为每个枚举常量导出实例的类。因为没有可访问的构造器,枚举类型是真正的final。既不能创建枚举类型实例,也不能对它进行扩张 。枚举类型是实例受控的,是单例的泛型化,本质上是氮元素的枚举 -《Effective Java》P129
public enum Singleton{

	INSTANCE;

	public void execute(){…}

	public static void main(String[] agrs){

		Singleton sole=Singleton.INSTANCE;

		sole.execute();

	}

}

  • 懒汉式 – Lazy initialization . 构造函数是private,只有通过Singleton才能实例化这个类。
public class Singleton{

	private volatile static Singleton uniqueInstance=null;

	private Singleton(){}

	public static Singleton getInstance(){

		if(uniqueInstance==null){

			synchronized(Singleton.class){

				if(uniqueInstance==null){

					uniqueInstance=new Singleton();

				}

			}

		}

		return uniqueInstance;

	}

	//other useful methods here

}
  • 饿汉式 – Eager initialization
public class Singleton{

	private static Singleton uniqueInstance=new Singleton();

	private Singleton(){}

	public static Singleton getInstance(){

		return uniqueInstance;

	}

}
  • static block initialization
public class Singleton{

	private static final Singleton instance;

		

	static{

		try{

			instance=new Singleton();

		}catch(IOException e){

			thronw new RuntimeException("an error's occurred!");

		}

	}

	public static Singleton getInstance(){

		return instance;

	}

	private Singleton(){

	}

}
  • The solution of Bill Pugh 。- From wiki <Singleton Pattern> 。通过静态成员类来实现,线程安全。
public class Singleton{

	//private constructor prevent instantiation from other classes

	private Singleton(){}

    

   	/**

    *SingletonHolder is loaded on the first execution of Singleton.getInstance()

    *or the first access to SingletonHolder.INSTANCE,not befor.

    */

     private static class SingletonHolder{

		public static final Singleton instance=new Singleton();

	 }

     private static Singleton getInstance(){

		return SingletonHolder.instance;

	 }

}

你可能感兴趣的:(Singleton)