这种一种lazy的写法,利用内部静态类的特性。又可以节约一个同步方法。

 1 public class BobLeeSingleton {
2
3 private static class Holder {
4 static BobLeeSingleton instance = new BobLeeSingleton();
5 }
6
7 private BobLeeSingleton() {
8 }
9
10 public static BobLeeSingleton getInstance() {
11 return Holder.instance;
12 }
13 }

 

这是一种利用enum实现的单例写法

public enum EnumSingleton {  
INSTANCE {
public void someMethod() {
System.out.println("INSTANCE.someMethod");
}
};

protected abstract void someMethod();

public static void main(String[] args) {
EnumSingleton instance = EnumSingleton.INSTANCE;
instance.someMethod();
}
}

 

还有一种实现是利用hashmap和Class.forName支持一组单列。这里就不重述了

相关文章:

  • 2021-09-29
  • 2021-12-19
  • 2022-12-23
  • 2022-12-23
  • 2021-08-23
  • 2021-11-20
猜你喜欢
  • 2022-12-23
  • 2021-07-20
  • 2021-09-15
  • 2022-12-23
  • 2021-11-09
  • 2021-12-06
  • 2021-08-09
相关资源
相似解决方案