• C#版常用设计模式入门


    单例模式

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 using System.Threading.Tasks;
     6 
     7 namespace BeginOfCSharp.DesignMode
     8 {
     9     /// <summary>
    10     /// 单例模式
    11     ///     单例类只能有一个实例,必须自己创建自己的唯一实例,必须给其它所有对象提供这一实例
    12     ///     单例模式拥有一个私有构造函数,使用户无法通过new来创建其它的实例
    13     ///                    静态私有成员变量,负责存储实例
    14     ///                    静态公有方法,负责检验并且实例化
    15     ///     单例可以实现“同步”的效果,如:避免了多个用户同时注册时,自动生成的主键重复(只有一个地方能分配下一个主键号)
    16     /// </summary>
    17     class Singleton
    18     {
    19         private static Singleton instance;
    20 
    21         protected Singleton() { }
    22 
    23         /// <summary>
    24         /// 实例化
    25         /// </summary>
    26         /// <returns>返回唯一实例</returns>
    27         public static Singleton GetInstance()
    28         { 
    29             if(instance == null)
    30                 instance = new Singleton();
    31             return instance;
    32         }
    33         
    34         static void Main(string[] args)
    35         {
    36             Singleton s1 = Singleton.GetInstance();
    37             Singleton s2 = Singleton.GetInstance();
    38             //检测这s1和s2是否是同一个实例(结果是True)
    39             Console.WriteLine(s1 == s2);
    40             Console.ReadLine();
    41         }
    42     }
    43 }
    一般单例
     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 using System.Threading.Tasks;
     6 
     7 namespace BeginOfCSharp.DesignMode
     8 {
     9     /// <summary>
    10     /// 利用.net平台优势实现的单例
    11     ///     代码量少,解决了线程问题带来的性能损失
    12     ///     sealed修饰类,所以该类不能被继承
    13     ///     instance成员变量在声明的时候就被初始化(所以无法实现延迟初始化)
    14     ///     public readonly修饰该instance,保证该变量以后不会再次实例化
    15     /// </summary>
    16     sealed class SingletonNet
    17     {
    18         private SingletonNet() { }
    19         public static readonly SingletonNet instance = new SingletonNet();
    20 
    21         static void Main(string[] args)
    22         {
    23             SingletonNet s1 = SingletonNet.instance;
    24             SingletonNet s2 = SingletonNet.instance;
    25             //检测这s1和s2是否是同一个实例(结果是True)
    26             Console.WriteLine(s1 == s2);
    27             Console.ReadLine();
    28         }
    29     }
    30 }
    利用.net平台优势实现的单例
  • 相关阅读:
    线性代数思维导图——3.向量
    微分中值定理的基础题型总结
    构造函数
    Python课程笔记(七)
    0241. Different Ways to Add Parentheses (M)
    0014. Longest Common Prefix (E)
    0013. Roman to Integer (E)
    0011. Container With Most Water (M)
    0010. Regular Expression Matching (H)
    0012. Integer to Roman (M)
  • 原文地址:https://www.cnblogs.com/coqn/p/DesignMode.html
Copyright © 2020-2023  润新知