标签:blog http io 使用 ar 数据 sp div on
单例(Singleton)设计模式保证每个类只有一个实例,并为这个实例提供一个全局的访问点。
与工具类中的静态成员不同,单例类一般用来保存应用程序的状态数据,这些数据在应用程序的各个部分都可能被访问或修改。
单例模式的几种实现方式。
1 public class Singleton{
2 private static Singleton instance = new Singleton();
3
4 public static Singleton getInstance() {
5 return instance;
6 }
7
8 /** Don‘t let anyone else instantiate this class */
9 private Singleton() {
10 }
11 }
这种方式实现简单,并且保证实例的唯一性,缺点是必须先加载后使用,而且不管单例类是否真正使用到,实例总是会先被加载,这看起来相当的不妥,因而有了懒加载(Lazy Initialization)的模式。
1 public class Singleton {
2 private static Singleton instance = null;
3
4 private Singleton() {
5
6 }
7
8 public static Singleton getInstance() {
9 if (instance == null) {
10 instance = new Singleton();
11 }
12 return instance;
13 }
14 }
这种方式可以实现懒加载,但当多个线程同时进入getInstance方法时,可能会产生多份实例,这显然违背单例模式的初衷。为了避免这种情况,考虑加上同步(synchronized)机制。
1 public class Singleton {
2 private static Singleton instance = null;
3
4 private Singleton(){
5 }
6
7 synchronized static public Singleton getInstance() {
8 if (instance == null) {
9 instance = new Singleton();
10 }
11 return instance;
12 }
13 }
这种方式可以在懒加载的同时保证只有一份实例,但对整个getInstance方法作同步处理会带来线程同步上的性能消耗。
1 public class Singleton {
2 private static Singleton instance;
3
4 private Singleton(){
5 }
6
7 public static Singleton getInstance() {
8 if (instance == null){
9 synchronized(Singleton.class){
10 if(instance == null) {
11 instance = new Singleton();
12 }
13 }
14 }
15 return instance;
16 }
17 }
标签:blog http io 使用 ar 数据 sp div on
原文地址:http://www.cnblogs.com/liangjq/p/3997899.html