大化设计模式-单例模式

  • 原理:保证一个类只有一个实例对象,提供一个对外的实例创建方法。

  • 好处
  1. 数据共享,多个线程可以共用一个实例,共同享用这个实例的资源属性(如数据库连接器)
  2. 线程安全,通过线程加锁,可以达到并发访问的目的
  3. 节约资源,防止创建过多不必要的对象

  • 结构图
    ![enter description here][1]

  • 分类
  1. 懒汉式:实例化调用时才实例化,否则就不实例化
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//懒汉式  
class Singleton {
private static Singleton instance;

private Singleton() {
}

public static Singleton GetInstance() {
if (NULL == instance) {
instance = new Singleton();
}
return instance;
}
};
  1. 多线程单例:多线程下,加锁
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//多线程情况下:  
class Singleton {
private static Singleton instance;
//加一个锁
private static readonly object sync = new object();

private Singleton() {
}

public static Singleton GetInstance() {
//先判断是否存在,再加锁!
if (NULL == instance) {
lock(sync) {
if (NULL == instance){
instance = new Singleton();
}
}
}
return instance;
}
};
  1. 饿汉式:通过静态修饰,使得在加载时就直接实例化,提前做准备。
1
2
3
4
5
6
7
8
9
10
11
//饿汉式  
public sealed class Singleton {
// 通过static final修饰,进行初始化加载,同时无法更改
private static final Singleton instance = new Singleton();
private Singleton() {
}

public static Singleton GetInstance(){
return instance;
}
};

Donate comment here