JAVA单例模式的理解

一、介绍
单例模式(Singleton Pattern),它是Java中最简单的设计模式之一,属于创建型模式的一种,它提供了一种创建对象的最佳方式。这种模式的意义在于保证一个类仅有一个实例

二、实现思路
创建一个类,将其默认构造方法私有化,使外界不能通过new Object来获取对象实例,同时提供一个对外获取对象唯一实例的方法。

例如,创建一个SingletonObject,如下:

public class SingletonObject {
	//创建SingletonObject的一个对象
	private static SingletonObject instance=new SingletonObject();
	
	//默认构造函数为private,该类不会被实例化
	private SingletonObject() {
		
	}
	
	//获取实例对象
	public static SingletonObject getInstance()
	{
		return instance;
	}
	
	public void showMessage() {
		System.out.println("Hello World!");
	}
}

从SingletonObject类中获取对象

public class SingletonTest {

	public static void main(String[] args) {
		// TODO 自动生成的方法存根
		//SingletonObject object=new SingletonObject();
		//构造函数 SingletonObject()不可视
		
		SingletonObject object=SingletonObject.getInstance();
		object.showMessage();
	}
}

结果:

三、单例模式的实现方式

1、懒汉式,线程不安全(不推荐)
最基本的实现方式,最大的问题就是不支持多线程。因为没有加锁synchronized,在多线程时不能正常工作。

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

2、加锁懒汉式,线程安全(不推荐)
优点:第一次调用才初始化,避免内存浪费。
缺点:必须加锁synchronized才能保证单例,但加锁会影响效率。

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

3、饿汉式(推荐使用)
优点:没有加锁,执行效率会提高
缺点:类加载时就初始化,浪费内存空间

这种方式基于classloader机制避免了多线程的同步问题,不过,instance在类装载时就实例化,虽然导致类装载的原因有很多,在单例模式中大多数是通过调用getInstance方法,但是还有其他方式能够导致类装载,这时候初始化instance显然没有达到lazy loading的效果。

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

4、 双重检查加锁(推荐使用)
采用双锁机制,安全且在多线程情况下能保持高性能。

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

5、静态内部类(推荐使用)
这种方式能达到双检锁方式一样的功效,对静态域使用延迟初始化,但实现更简单。这种方式只适用于静态域的情况,双检锁方式可在实例域需要延迟初始化时使用。

public class Singleton{
	private static class SingletonDo{
		private static Singleton INSTANCE=new Singleton();
	}
	
	private Singleton(){}

	public static Singleton getInstance(){
		return SingletonDo.INSTANCE;
	}
}

6、枚举(推荐使用)
这种方式还没有被广泛采用,但这是实现单例模式的最佳方法。它更简洁,自动支持序列化机制,绝对防止多次实例化。

public enum Singleton{
	INSTANCE;
	public void doMethod(){
	
	}
}

四、应用
单例模式在Java中的应用也很多,例如Runtime就是一个典型的例子,源码如下:

public class Runtime {
    private static Runtime currentRuntime = new Runtime();

    /**
     * Returns the runtime object associated with the current Java application.
     * Most of the methods of class <code>Runtime</code> are instance
     * methods and must be invoked with respect to the current runtime object.
     *
     * @return  the <code>Runtime</code> object associated with the current
     *          Java application.
     */
    public static Runtime getRuntime() {
        return currentRuntime;
    }

    /** Don't let anyone else instantiate this class */
    private Runtime() {}
    
    ... ...

它使用了饿汉式方式创建单例对象。

五、总结
一般情况下,不建议使用第1种和第2种懒汉方式,建议使用第三种饿汉方式。只有在要明确实现lazy loading效果时,才会使用第5种登记方式。如果涉及到反序列化创建对象时,可以尝试使用第6种枚举方式。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值