四中方式实现单例模式

一:饿汉式单例模式

package com.zkn.newlearn.gof.singleton;

/**
 *
 * 饿汉式单例模式
 * @author zkn
 *
 */

public class SingletonTest01{

	/**
	 * 加载类时,立即加载对象,是没有延迟的。是天然的线程安全的
	 */
	private static SingletonTest01 singleton = new SingletonTest01();
	
	/**
	 *  构造器私有化
	 */
	private SingletonTest01() {
		
	}
	/**
	 * 返回这个对象
	 */
	public static SingletonTest01 getInstance(){
		
		return singleton;
	}
	
	public void test(){
		System.out.println("我是饿汉式单例模式");
	}
	
}


二:懒汉式单例模式

package com.zkn.newlearn.gof.singleton;

/**
 * 
 * @author zkn
 *
 */

public class SingletonTest02 {

	private static SingletonTest02 singleton;
	
	/**
	 * 构造器私有化
	 */
	private SingletonTest02() {
		
	}

	public static synchronized SingletonTest02 getInstance(){
		
		if(singleton == null){
			singleton = new SingletonTest02();
		}
		return singleton;
	}
	
	public void test(){
		System.out.println("我是懒汉是单例模式");
	}
}


三:静态内部类

package com.zkn.newlearn.gof.singleton;

/**
 * 静态内部类  线程安全 延迟加载 调用效率高
 * @author zkn
 *
 */


public class SingletonTest04 {

	private static class SingletonClassInstance{
		private static final SingletonTest04 single = new SingletonTest04(); 
	}
	
	private SingletonTest04() {
		
	}

	public static SingletonTest04 getInstance() {
		
		return SingletonClassInstance.single;
	}
	
}


四:枚举(单元素)

package com.zkn.newlearn.gof.singleton;

/**
 * 
 * 枚举实现单例 避免反射漏洞 jvm层面是安全的
 * @author zkn
 *
 */

public enum SingletonTest05 {

	/**
	 * 枚举元素本身就是单例
	 */
	INSTANCE;
}

猜你喜欢

转载自zknxx.iteye.com/blog/2301607