单例模式是我们开发中常用的一种设计模式,今天结合JBPM来学习这个模式。本来打算先分析JBPM中的单例模式,然后总结单例模式;但是JBPM的实现并不是完全符合GOF中队单例模式的完成定义,其实现跟自己的业务有一定的关联。那么我们就先来学习严格意义上的单例模式,然后再分析JBPM实现的单例模式。
单例模式定义
保证一个类仅有一个实例,并提供一个访问它的全局访问点让类自己负责实例的生成,并提供访问该实例的方法
在我们实际的开发中,很多时候我们需要控制某个类的实例化,并且需要控制其只能实例化一个实例;其中一个最好的方法就是让这个类负责自己的实例化,并且保证不会有其他的实例被创建,同时向外提供一个访问唯一实例的方法。这样单例模式控制了何时和怎么访问自己的实例对象。
典型代码实例
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace WFTHSingletonCA
7 {
8 public class WFTHSingleton
9 {
10 private static WFTHSingleton singleton = null;
11 private static object lockObj = new object();
12
13 private WFTHSingleton()
14 {
15
16 }
17
18 public static WFTHSingleton GetWFTHSingleton()
19 {
20 if (singleton==null)
21 {
22 lock(lockObj)
23 {
24 if(singleton==null)
25 {
26 singleton = new WFTHSingleton();
27 }
28 }
29 }
30 return singleton;
31 }
32 }
33 }
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5
6 namespace WFTHSingletonCA
7 {
8 public class WFTHSingleton
9 {
10 private static WFTHSingleton singleton = null;
11 private static object lockObj = new object();
12
13 private WFTHSingleton()
14 {
15
16 }
17
18 public static WFTHSingleton GetWFTHSingleton()
19 {
20 if (singleton==null)
21 {
22 lock(lockObj)
23 {
24 if(singleton==null)
25 {
26 singleton = new WFTHSingleton();
27 }
28 }
29 }
30 return singleton;
31 }
32 }
33 }