漫谈设计模式(三)单例(Singleton)模式

如果要保证系统里一个类最多自能存在一个实例,我们就要使用单例模式


最简单的单例模式

package com.model.sigleton;

public class Singleton {

	private static Singleton singleton = new Singleton();

	/**
	 * 唯一的构造方法被private修饰,表示外部无法通过构造反法创建对象
	 */
	private Singleton() {

	}

	public static Singleton getInstance() {
		return singleton;
	}

}



进阶-延迟创建且线程安全
  出于性能方面考虑,我们希望延迟实例化单例对象(Static属性在加载类时就会被初始化),只有在第一次使用该类的实例时才去实例化,我们应该怎么办呢?
package com.model.sigleton;

/**
 * 
 * @author leo Chen
 *
 */

public class UnThreadSafeSingelton {
	private static UnThreadSafeSingelton instatnce;

	// variables and constructors...

	/**
	 * 
	 * @return
	 */
	public static synchronized UnThreadSafeSingelton getInstance() {
		if (instatnce == null) {
			instatnce = new UnThreadSafeSingelton();
		}

		return instatnce;
	}

}


doublecheck locking模式

package com.model.sigleton;

public class DoubleCheckSingleton {

	private volatile static DoubleCheckSingleton instantnce = null;

	// constructors

	public static DoubleCheckSingleton getInstance() {
		if (instantnce == null) {// check if it is created.
			synchronized (DoubleCheckSingleton.class) {
				if (instantnce == null) {
					instantnce = new DoubleCheckSingleton();
				}
			}

		}
		return instantnce;
	}

}



lazyLoadedSingleton
package com.model.sigleton;

public class LazyLoadedSingleton {

	private LazyLoadedSingleton() {

	}

	private static class LazyHolder {
		private static final LazyLoadedSingleton LAZY_LOADED_SINGLETON = new LazyLoadedSingleton();
	}

	public static LazyLoadedSingleton getInstance() {
		return LazyHolder.LAZY_LOADED_SINGLETON;
	}

}


当JVM加载lazyLoadedSingleton类时,由于该类没有static属性,所以加载完成后便即可返回,只有第一次调用getInstance()方法时,JVM才会加载LazyHolder,由于它包含static属性,所以会先初始化这个变量,根据前面过程介绍,我们知道此过程并不会出现并发问题(JLS保证),这样即实现了一个既保证现成安全又支持延迟加载的单例模式

Singleton的序列化

package com.model.sigleton;

import java.io.Serializable;

public class Singleton implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private static Singleton singleton = new Singleton();

	/**
	 * 唯一的构造方法被private修饰,表示外部无法通过构造反法创建对象
	 */
	private Singleton() {

	}

	public static Singleton getInstance() {
		return singleton;
	}

	private Object readResolve() {
		return singleton;
	}

}





猜你喜欢

转载自buyaozaibeidaole.iteye.com/blog/2249092