新看到三种单例模式,备忘

 

这种一种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支持一组单列。这里就不重述了

posted @ 2012-01-12 19:05  倚楼无语F5  阅读(236)  评论(0编辑  收藏  举报