Singleton三种实现方法(effective java笔记)

public enum SingletonEnum {

	/**枚举类型方法
	 * 此方法更为简洁,无偿提供了序列化机制,当然也防止了多次实例化(即使在复杂序列化和发射时)
	 * 单元素枚举类型已经成为实现singleton的最佳方法
	 * @param args
	 */
	INSTANCE;
	public void doWork(){
		System.out.println("Enum Singleton dowork");
	}

  }

public class SingletonPubField {

	/**公有域方法
	 *  
	 */
	public static final SingletonPubField INSTANCE = new SingletonPubField();
	public void doWork(){
		System.out.println("PubField SingletonPub dowork");
	}

}

public class SingletonStFactory {

	/**静态工厂方法
	 * @param args
	 */
	private static final SingletonStFactory INSTANCE = new SingletonStFactory();;
	public SingletonStFactory() {
	}
	public static SingletonStFactory getInstance(){
		return INSTANCE;
	}
	public void doWork(){
		System.out.println("staticfactory singleton dowork");
	}
}

public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		 SEnum();
		 SPubF();
		 SStF();
	}
	
	public static void SEnum(){
		SingletonEnum.INSTANCE.doWork();
	}
	public static void SPubF(){
		SingletonPubField.INSTANCE.doWork();
	}
	public static void SStF(){
		SingletonStFactory.getInstance().doWork();
	}

}

你可能感兴趣的:(Effective Java)