• 单例模式


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

    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("");
            }
        }
  • 相关阅读:
    php模拟发送GET和POST请求
    php获取从百度搜索进入网站的关键词
    HDU 6218 (线段树+set)
    Wannafly挑战赛2_D Delete(拓扑序+最短路+线段树)
    BZOJ3926 (后缀自动机)
    Codeforces 848C (cdq分治)
    CERC 2014 (动态树+主席树)
    UOJ 58 (树上带修改的莫队)
    UVA12345 (带修改的莫队)
    BZOJ2038 (莫队)
  • 原文地址:https://www.cnblogs.com/LY-NET/p/11875625.html
Copyright © 2020-2023  润新知