zoukankan      html  css  js  c++  java
  • C#单例模式的懒汉与饿汉

    ※ 单 例 模 式

        单例模式是指某一类在被调用时只能创建一个实例,即只能new一次;

    ※  饿 汉

        在每次调用的时候都先加载;

    ※  懒 汉

         调用的时候不加载,需要用到再加载;在多线程调用时不安全;

       (注意:在Nuity3D中不存在多线程,所以两种模式都可以用,相对来说,懒汉模式用的多一点)

       饿汉模式  C#代码

    1  class HungerSingleton {
    2         private static HungerSingleton _hungerSingleton=new HungerSingleton();
    3        
    4         private  HungerSingleton() { }
    5         public static HungerSingleton GetInstance() {
    6             Console.WriteLine("hunger");
    7             return _hungerSingleton;            
    8         }  
    9     }

       懒汉模式  C#代码

     1  class LazySingleton {
     2         private static LazySingleton _LazySingleton;
     3         private LazySingleton() { }
     4         public static LazySingleton GetInstance() {
     5             if (_LazySingleton==null)
     6             {
     7                 Console.WriteLine("lazy");
     8                 _LazySingleton = new LazySingleton();
     9             }
    10             return _LazySingleton;
    11         }
    12     }
  • 相关阅读:
    视频遮挡问题
    calc兼容性
    javascript变量声明提升
    jquery插件
    prop和attr在 jquery的
    onclick防止冒泡和json对象放入
    git 入门
    去掉ie滚动条兼容性
    单页面应用程序(SPA)
    swiper轮播图插件
  • 原文地址:https://www.cnblogs.com/RainPaint/p/9890154.html
Copyright © 2011-2022 走看看