首页 > 其他 > 详细

单例模式

时间:2019-11-17 11:57:19      阅读:78      评论:0      收藏:0      [点我收藏+]

使用单例模式的目的:单例模式就是保证在整个应用程序的生命周期中,在任何时刻,被指定的类只有一个实例,并为客户程序提供一个获取该实例的全局访问点。

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("");
        }
    }

 

单例模式

原文:https://www.cnblogs.com/LY-NET/p/11875625.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!