













VS 2008
使用单例模式,可以控制一个类在一个应用程序中只有一个实例。
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;
}
}
}

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;
}
}
}

此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。