[代码]Java中的五种单例模式实现方法 跳至 [1] [全屏预览]
01 | package singleton; |
02 |
03 | /** |
04 | * @author lei |
05 | * 单例模式的五种写法: |
06 | * 1、懒汉 |
07 | * 2、恶汉 |
08 | * 3、静态内部类 |
09 | * 4、枚举 |
10 | * 5、双重校验锁 |
11 | * 2011-9-6 |
12 | */ |
13 | /** |
14 | *五、 双重校验锁,在当前的内存模型中无效 |
15 | */ |
16 | class LockSingleton{ |
17 | private volatile static LockSingleton singleton; |
18 | private LockSingleton(){} |
19 | |
20 | //详见:http://www.ibm.com/developerworks/cn/java/j-dcl.html |
21 | public static LockSingleton getInstance(){ |
22 | if (singleton== null ){ |
23 | synchronized (LockSingleton. class ){ |
24 | if (singleton== null ){ |
25 | singleton= new LockSingleton(); |
26 | } |
27 | } |
28 | } |
29 | return singleton; |
30 | } |
31 | |
32 | } |
33 | /** |
34 | * 四、枚举,《Effective Java》作者推荐使用的方法,优点:不仅能避免多线程同步问题,而且还能防止反序列化重新创建新的对象 |
35 | */ |
36 | enum EnumSingleton{ |
37 | INSTANCE; |
38 | public void doSomeThing(){ |
39 | } |
40 | } |
41 | /** |
42 | * 三、静态内部类 优点:加载时不会初始化静态变量INSTANCE,因为没有主动使用,达到Lazy loading |
43 | */ |
44 | class InternalSingleton{ |
45 | private static class SingletonHolder{ |
46 | private final static InternalSingleton INSTANCE= new InternalSingleton(); |
47 | } |
48 | private InternalSingleton(){} |
49 | public static InternalSingleton getInstance(){ |
50 | return SingletonHolder.INSTANCE; |
51 | } |
52 | } |
53 | /** |
54 | * 二、恶汉,缺点:没有达到lazy loading的效果 |
55 | */ |
56 | class HungrySingleton{ |
57 | private static HungrySingleton singleton= new HungrySingleton(); |
58 | private HungrySingleton(){} |
59 | public static HungrySingleton getInstance(){ |
60 | return singleton; |
61 | } |
62 | } |
63 | /** |
64 | * 一、懒汉,常用的写法 |
65 | */ |
66 | class LazySingleton{ |
67 | private static LazySingleton singleton; |
68 | private LazySingleton(){ |
69 | } |
70 | public static LazySingleton getInstance(){ |
71 | if (singleton== null ){ |
72 | singleton= new LazySingleton(); |
73 | } |
74 | return singleton; |
75 | } |
76 | } |