当前位置导航:炫浪网>>网络学院>>编程开发>>JAVA教程>>Java进阶

singleton的几种实现方式

    1.Eager

public class EagerInitialization {
private static Resource resource = new Resource();
public static Resource getResource() {
return resource;
}
static class Resource {
}
}

    2.Lazy

public class SafeLazyInitialization {
private static Resource resource;
public synchronized static Resource getInstance() {
if (resource == null)
resource = new Resource();
return resource;
}
static class Resource {
}
}

    3.double checked locking singleton ( 仅适用于java 5.0 以上版本)

public class DoubleCheckedLockingSingleton {
//java5.0 修改了内存模型, 可以保证使用volatile 声明的变量对于double checked locking是正确的
private volatile static DoubleCheckedLockingSingleton uniqueInstance;

private DoubleCheckedLockingSingleton() {}

public static DoubleCheckedLockingSingleton getInstance() {
if (uniqueInstance == null) {
synchronized (DoubleCheckedLockingSingleton.class) {
if (uniqueInstance == null) {
uniqueInstance = new DoubleCheckedLockingSingleton();
}

}
}

return uniqueInstance;
}
}

    4.Lazy initialization holder class idiom

public class ResourceFactory {
//增加一个helper类来初始化对象
private static class ResourceHolder {
public static Resource resource = new Resource();
}
public static Resource getResource() {
return ResourceFactory.ResourceHolder.resource;
}
static class Resource {
}
}

    以上四种方法都是线程安全的实现方式。
相关内容
赞助商链接