zoukankan      html  css  js  c++  java
  • 单件模式

    保证一个类仅有一个实例,并提供一个访问它的全局访问点。

    image_2


    1.示例1.
    由于加了readonly关键字,所以只会在构造函数中初始化一次.

    public sealed class Singleton {
       // Private Constructor 
       Singleton() { }
       
       // Private object instantiated with private constructor
       static readonly Singleton instance = new Singleton();
     
       // Public static property to get the object
       public static Singleton UniqueInstance {
         get { return instance;}
       }
     }


    2.延迟初始化

    注意内部多定义了一个类

    public class Singleton {
       // Private constructor 
       Singleton () { }
       
       // Nested class for lazy instantiation
       class SingletonCreator {
         static SingletonCreator () {}
         // Private object instantiated with private constructor
         internal static readonly 
         Singleton uniqueInstance = new Singleton();
       }
     
       // Public static property to get the object
       public static Singleton UniqueInstance {
         get {return SingletonCreator.uniqueInstance;}
       }
     }

    这个模式平时用到的也最多,面试的人也很喜欢问这个,属于基本模式,简单也不容易忘记,自然大家都喜欢问,呵呵

  • 相关阅读:
    排列 [计数dp]
    排列 [计数dp]
    函数 [计数]
    多态
    继承2
    2018年蓝桥杯b组国赛真题
    c++的继承
    运算符2
    运算符重载
    拷贝构造
  • 原文地址:https://www.cnblogs.com/Clingingboy/p/1809560.html
Copyright © 2011-2022 走看看