Java单例模式Singleton的几种实现方式

阅读更多
请参考链接:
Singleton Design Pattern in Java
http://howtodoinjava.com/design-patterns/creational/singleton-design-pattern-in-java/



1) Recommendation way
public class DemoSingleton implements Serializable {
	private static final long serialVersionUID = 1L;

	private DemoSingleton() {
		// private constructor
	}

	private static class DemoSingletonHolder {
		public static final DemoSingleton INSTANCE = new DemoSingleton();
	}

	public static DemoSingleton getInstance() {
		return DemoSingletonHolder.INSTANCE;
	}

	protected Object readResolve() {
		return getInstance();
	}
}


2) minimum effort way

This type of implementation recommend the use of enum. Enum, as written in java docs, provide implicit support for thread safety and only one instance is guaranteed. This is also a good way to have singleton with minimum effort.

public enum EnumSingleton {
    INSTANCE;
    public void someMethod(String param) {
        // some class member
    }
}

你可能感兴趣的:(java,singleton,单例,单子,模式)