[size=medium]请参考链接:
Singleton Design Pattern in Java
[url]http://howtodoinjava.com/design-patterns/creational/singleton-design-pattern-in-java/[/url]
[/size]
1) Recommendation way
2) minimum effort way
[size=medium]
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.
[/size]
Singleton Design Pattern in Java
[url]http://howtodoinjava.com/design-patterns/creational/singleton-design-pattern-in-java/[/url]
[/size]
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
[size=medium]
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.
[/size]
public enum EnumSingleton {
INSTANCE;
public void someMethod(String param) {
// some class member
}
}