问题:编写一个Singleton类
简单的方式
1 package cn.changb.singleton;
2
3 /**
4 * 简单的方式:弊端是在并发执行时,14行处可能存在多个实例
5 */
6 public class SingletonDemo1 {
7 private static SingletonDemo1 INSTANCE;
8
9 private SingletonDemo1() {
10 }
11
12 public static SingletonDemo1 getInstance() {
13 if (INSTANCE == null) {
14 INSTANCE = new SingletonDemo1();
15 }
16 return INSTANCE;
17 }
18 }
公共域方式
1 package cn.changb.singleton;
2
3 /**
4 * 公共域方式:简单,不存在并发出现多实例的问题,但弊端是返回实例时增加一些额外的逻辑
5 */
6 public class SingletonDemo2 {
7 public static final SingletonDemo2 INSTANCE = new SingletonDemo2();
8
9 private SingletonDemo2() {
10 }
11 }
工厂化方式
1 package cn.changb.singleton;
2
3 /**
4 * 工厂化方式:可以在实例化过程中(11行处)添加逻辑
5 */
6 public class SingletonDemo3 {
7 private static final SingletonDemo3 INSTANCE = new SingletonDemo3();
8
9 private SingletonDemo3() {
10 }
11
12 public static SingletonDemo3 getInstance() {
13 return INSTANCE;
14 }
15 }
枚举类方式
1 package cn.changb.singleton;
2
3 /**
4 * 枚举类方式:最佳实践,推荐方式
5 *
6 * 不存在多个实例问题、反序列化问题!
7 */
8 public enum SingletonDemo4 {
9 INSTANCE;
10 }
SingletonTest
1 package cn.changb.singleton;
2
3 public class SingletonTest {
4
5 public static void main(String[] args) {
6 // TODO Auto-generated method stub
7 System.out.println("SingletonDemo1" + SingletonDemo1.getInstance());
8 System.out.println("SingletonDemo1" + SingletonDemo1.getInstance());
9
10 System.out.println("SingletonDemo2" + SingletonDemo2.INSTANCE);
11 System.out.println("SingletonDemo2" + SingletonDemo2.INSTANCE);
12
13 System.out.println("SingletonDemo3" + SingletonDemo3.getInstance());
14 System.out.println("SingletonDemo3" + SingletonDemo3.getInstance());
15
16 System.out.println("SingletonDemo4" + SingletonDemo4.INSTANCE);
17 System.out.println("SingletonDemo4" + SingletonDemo4.INSTANCE);
18 }
19
20 }