java单例的几种实现方法
2015-08-31 20:38 Rollen Holt 阅读(2104) 评论(0) 编辑 收藏 举报java单例的几种实现方法:
方式1:
public class Something {
private Something() {}
private static class LazyHolder {
private static final Something INSTANCE = new Something();
}
public static Something getInstance() {
return LazyHolder.INSTANCE;
}
}
方式2:
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
}
方式3:
public class Singleton {
private static final Singleton instance;
static {
try {
instance = new Singleton();
} catch (Exception e) {
throw new RuntimeException("Darn, an error occurred!", e);
}
}
public static Singleton getInstance() {
return instance;
}
private Singleton() {
// ...
}
}
方式4:
public enum Singleton {
INSTANCE;
public void execute (String arg) {
// Perform operation here
}
}
方式5:
public class SingletonDemo {
private static volatile SingletonDemo instance;
private SingletonDemo() { }
public static SingletonDemo getInstance() {
if (instance == null ) {
synchronized (SingletonDemo.class) {
if (instance == null) {
instance = new SingletonDemo();
}
}
}
return instance;
}
}
方式6:
使用apache commons lang: LazyInitializer
public class ComplexObjectInitializer extends LazyInitializer<ComplexObject> {
@Override
protected ComplexObject initialize() {
return new ComplexObject();
}
}
// Create an instance of the lazy initializer
ComplexObjectInitializer initializer = new ComplexObjectInitializer();
...
// When the object is actually needed:
ComplexObject cobj = initializer.get();
方式7:
使用guava:
private static final Supplier<String> tokenSup = Suppliers.memoize(new Supplier<String>() {
@Override
public String get() {
//do some init
String result = xxx;
return result;
}
});
==============================================================================
本博客已经废弃,不在维护。新博客地址:http://wenchao.ren
我喜欢程序员,他们单纯、固执、容易体会到成就感;面对压力,能够挑灯夜战不眠不休;面对困难,能够迎难而上挑战自我。他
们也会感到困惑与傍徨,但每个程序员的心中都有一个比尔盖茨或是乔布斯的梦想“用智慧开创属于自己的事业”。我想说的是,其
实我是一个程序员
==============================================================================