package org.hq.singleton;

/**
 * @author HuangQiang
 * @date 2015-3-25
 * 
 *       单例模式的3种写法 用私有构造器或者枚举类型强化Singleton属性。
 *       单元素枚举类型方法是最佳的方法，可以应对序列化和反射等问题。
 */
public class Elvis {

	// 1.public静态成员是个final域
	static class Singleton1 {
		public static final Singleton1 INSTANCE = new Singleton1();

		private Singleton1() {
		}
	}

	// 2.静态工厂方法
	static class Singleton2 {
		private static final Singleton2 INSTANCE = new Singleton2();;

		private Singleton2() {
		}

		public static Singleton2 getInstance() {
			return INSTANCE;
		}
	}

	// 3.包含单个元素的枚举类型。最佳方法
	public static enum Singleton3 {
		INSTANCE;
		public void leaveTheBuilding() {
			System.out.println("so great.");
		}
	}

	public static void main(String[] args) {
		Elvis.Singleton3 a = Elvis.Singleton3.INSTANCE;
		Elvis.Singleton3 b = Elvis.Singleton3.INSTANCE;
		a.leaveTheBuilding();
		b.leaveTheBuilding();
	}
}

@@ -114,25 +114,16 @@
 leton%E5%B1%9E%E6%80%A7%E3%80%82
-%0A *      
  %E5%8D%95%E5%85%83%E7%B4%A0%E6%9E%9A%E4%B8%BE%E7%B1%BB%E5%9E%8B
@@ -146,16 +146,16 @@
 %E5%92%8C%E5%8F%8D%E5%B0%84%E7%AD%89%E9%97%AE%E9%A2%98%E3%80%82%0A
+
  */%0Apubl
@@ -422,17 +422,16 @@
 eton2();
-;
 %0A%0A%09%09priv
@@ -593,16 +593,17 @@
 STANCE;%0A
+%0A
 %09%09public
@@ -673,16 +673,281 @@
 %09%09%7D%0A%09%7D%0A%0A
+%09// 4.%E9%9D%99%E6%80%81%E5%B7%A5%E5%8E%82%E6%96%B9%E6%B3%95 --%E5%BB%B6%E8%BF%9F%E5%88%9D%E5%A7%8B%E5%8C%96%0A%09static class Singleton4 %7B%0A%09%09private Singleton4() %7B%0A%09%09%7D%0A%0A%09%09public static Singleton4 getInstance() %7B%0A%09%09%09return SingletonInner.INSTANCE;%0A%09%09%7D%0A%0A%09%09static class SingletonInner %7B%0A%09%09%09public static final Singleton4 INSTANCE = new Singleton4();;%0A%09%09%7D%0A%09%7D%0A%0A
 %09public 
@@ -1104,16 +1104,16 @@
 ding();%0A
-
 %09%09b.leav
@@ -1128,13 +1128,68 @@
 ding();%0A
+%09%09Elvis.Singleton4 d = Elvis.Singleton4.getInstance();%0A
 %09%7D%0A%7D%0A

add 静态工厂方法 --延迟初始化