使用单例模式的目的:单例模式就是保证在整个应用程序的生命周期中,在任何时刻,被指定的类只有一个实例,并为客户程序提供一个获取该实例的全局访问点。
1.首先为了咱不每一个需要单例的类都去写一遍单例,所以咱通过c#无敌的泛型来写一个单例的实现过程方法:
//单例模式 中间商
public class Singleton<T> where T : new() //where T : new()为泛型约束,通俗来说就是确保T类型是可以被new的
{
private static T _instance; //私有的T类型的静态变量
public static T GetInstance() //获取实例的函数
{
if (_instance == null) //判断实例是否已存在
{
_instance = new T(); //不存在则创建新的实例
}
return _instance; //返回实例
}
}
2.当咱们某个类需要单例的时候就可以继承中间商来进行单例了
1 public class SingLetonDemo : Singleton<SingLetonDemo>
2 {
3 public void SingLetonFun()
4 {
5 Console.WriteLine("SingLetonFun2,SingLetonFactory");
6 Console.ReadKey();
7 }
8 }
3.当我们需要在外部调用时只需要:
class Program
{
static void Main(string[] args)
{
SingLetonDemo.GetInstance().SingLetonFun();
Console.WriteLine("");
}
}