Core Design Patterns(10) Singleton 单例模式
VS 2008
使用单例模式,可以控制一个类在一个应用程序中只有一个实例。
1. 模式UML图
2. 代码示意
2.1 最简单的单例模式
2.2 Lazy instantiation and double checked locking
使用单例模式,可以控制一个类在一个应用程序中只有一个实例。
1. 模式UML图
2. 代码示意
2.1 最简单的单例模式
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DesignPattern.Singleton.BLL {
public class Singleton {
private static Singleton singleton = new Singleton();
private Singleton() { }
public static Singleton GetInstance() {
return singleton;
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DesignPattern.Singleton.BLL {
public class Singleton {
private static Singleton singleton = new Singleton();
private Singleton() { }
public static Singleton GetInstance() {
return singleton;
}
}
}
2.2 Lazy instantiation and double checked locking
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DesignPattern.Singleton.BLL {
public class LazySingleton {
private static LazySingleton singleton = null;
private static object objLock = new object();
private LazySingleton() { }
public static LazySingleton GetInstance() {
if (singleton == null) {
lock (objLock) {
if (singleton == null) {
singleton = new LazySingleton();
}
}
}
return singleton;
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DesignPattern.Singleton.BLL {
public class LazySingleton {
private static LazySingleton singleton = null;
private static object objLock = new object();
private LazySingleton() { }
public static LazySingleton GetInstance() {
if (singleton == null) {
lock (objLock) {
if (singleton == null) {
singleton = new LazySingleton();
}
}
}
return singleton;
}
}
}