SingleTon Pattern in C#.net

本文详细介绍了单例模式的实现方式及其在.NET Framework中的应用。包括简单的单例模式实现及线程安全的单例模式实现,并提供了代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The Singleton pattern ensures that a class only has one instance and provides a global point of access to it from a well-known access point. The class implemented using this pattern is responsible for keeping track of its sole instance rather than relying on global variables to single instances of objects.

Singleton Pattern Code


   

namespace DesignPatterns
{
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton()
{
}

public static Singleton Instance
{
get
{
return instance;
}
}
}
}

// code to access the Singleton.
using System.Diagnostics;
using DesignPatterns;
Trace.WriteLine(Singleton.Instance.ToString());


Explanation


First, you'll notice that the Singleton's constructor is set to private. This ensures that no other code in your application will be able to create an instance of this class. This enforces the requirement that there ever only be one instance of this class. 

Then, an instance member variable is defined of the same type as the class. This instance member is used to hold the only instance of our class. The variable is static so that it is defined only once. In the .NET Framework, static variables are defined at a point before their first use (that's the actual description of their implementation). Also, the instance variable is readonly so that it cannot be modified - not even by any code that you may write in the class's implementation. 

And, a public Instance property is defined with only a get method that way callers can access the instance of this class without ever being able to change it. The property is also static to provide global access from anywhere in your program. This ensures the global point of access requirement for the Singleton. 

Finally, to test the code, you can run code that accesses your Singleton class. As you can see above, it's easy enough to get at the instance of your class: 

Singleton.Instance; 

Place a breakpoint in instance member variable definition and another one in the Instance property get code, then run the Debugger on this code. You will notice that the member variable creation is hit just before the call to the Instance property. Also, if you place multiple calls to Singleton.Instance, you will notice that the instance member variable is only the first time, all other calls just return the cached instance variable. 

And, that is the only way to get an instance of a singleton class. If you try to create an instance of the Singleton class using the new operator: 

Singleton NewInstance = new Singleton(); 

Than, you will get a compiler error stating that the class cannot be created because the constructor is inaccessible due to its protection level. 

Thread-Safe Singleton Code

The previous code is the simplest implementation of a Singleton and can be used for most purposes. Typical WinForms applications runs in the UI thread, so the simple singleton will provide you with the functionality that you're looking for. However, if you are creating a multi-threaded application that needs to access a singleton across all of its threads, then you will need to create a thread-safe singleton class instead. What you gain in functionality comes at the cost of some performance, so you shouldn't use this form of the class unless you actually intend to use the class from multiple threads. 

namespace DesignPatterns

{
public sealed class MTSingleton
{
private static volatile MTSingleton instance = null;
private static object syncRoot = new object();
private MTSingleton()
{

}

public static MTSingleton Instance
{
get
{
if (instance == null)
{
lock(syncRoot)
{
if (instance == null)
instance = new MTSingleton();
}
}
return instance;
}
}
}
}
// code to access the Singleton.

using System.Diagnostics;
using DesignPatterns;
Trace.WriteLine(MTSingleton.Instance.ToString());



As you can see, this class is similar in structure to the Singleton class. The instance member variable is no longer set at creation time, but in the Instance property instead. The instance variable is declared to be volatile in order to assure that the assignment of instance complete before the instance can be accessed. 

The syncRoot object is used to lock on. The lock ensures that only one thread can access the instance creation code at once. That way, you won't get into a situation where two different threads are trying to create the singleton simultaneously. 

And, you'll notice that we double-check the existence of the instance variable within the locked code to be sure that exactly one instance is ever created. 

Finally, in your application code, access to the MTSingleton class is done in exactly the same way as with the simple singleton. 


Conclusion 

The Singleton design pattern has proven to be a useful pattern in many programs that I've written. Now, the code in this tutorial shows how to implement that same pattern in the .NET Framework.


转自:http://www.dotnetfunda.com/articles/article69.aspx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值