用C#来说明设计模式(一)单件模式
最近看了一些C#来描述设计模式的资料。也听了Microsoft做的讲座。想总结一下。在http://www.dofactory.com里面看到了用C#描述的设计模式,觉得以前自己做的软件不好。因为经常修改软件使我很痛苦,所以决定痛改前非。
这里说说自己经常会用到的模式
1. 单件模式
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnpatterns/html/ImpSingletonInCsharp.asp
在创建型中的单件模式相信大家都用到过。
通用方式:
using System;
public class Singleton
{
private static Singleton instance;
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
Static Initialization 静态初始化
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton(){}
public static Singleton Instance
{
get { return instance; }
}
}
线程安全代码:
public sealed class Singleton
{
private static volatile Singleton instance;
private static object syncRoot = new Object();
private Singleton() {}
public static Singleton Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
}
不管在任何情况下 :Ensure a class has only one instance and provide a global point of access to it.(确保类只有一个实例并且在程序中只有一个全局访问点)。上面的三个代码,第一和第二是一样的。第三是在多线程的环境中使用。
浙公网安备 33010602011771号