单例模式的四种实现

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 {
}
}

以上四种方法都是线程安全的实现方式。

你可能感兴趣的:(单例模式)