1 /**
2 * 经典的单例模式实现
3 */
4 public class Singleton{
5 private static Singleton uniqueInstance;
6
7 private Singleton(){}
8
9 public static Singleton getInstance(){
10 if(uniqueInstance == null){
11 uniqueInstance = new Singleton();
12 }
13 return uniqueInstance;
14 }
15 }
16 /**
17 * 单件模式确保一个类只有一个实例,并提供一个全局访问点
18 */
19 /*
20 * 处理多线程:
21 * 用synchronized修饰getInstance
22 * public static synchronized Singleton getInstance(){}
23 * 每次调用这个方法,同步是一种累赘
24 */
25
26 /*
27 * 急切创建实例:JVM在加载这个类时马上创建唯一的单件实例
28 */
29 public class Singleton{
30 private static Singleton uniqueInstance = new Singleton();
31
32 private Singleton(){}
33
34 public static Singleton getInstance(){
35 return uniqueInstance;
36 }
37 }
38 /**
39 * 双重检查加锁
40 */
41 public class Singleton{
42 private volatile static Singleton uniqueInstance;
43
44 private Singleton(){}
45
46 public static Singleton getInstance(){
47 if(uniqueInstance == null){
48 synchronized(Singleton.class){
49 if(uniqueInstance == null)
50 uniqueInstance = new Singleton();
51 }
52 }
53 return uniqueInstance;
54 }
55 }