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;
	 }
}

转载于:https://www.cnblogs.com/matt123/archive/2012/06/26/2564393.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值