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

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 
     6 namespace 单例模式
     7 {
     8     class Studnet
     9     {
    10         public string id { get; set; }
    11         public string name { get; set; }
    12 
    13         private static Studnet _instance = null;
    14 
    15         private Studnet()
    16         {
    17 
    18         }
    19 
    20 
    21         //单例第一种写法
    22 
    23         private static object _SingleLock = new object();
    24         public static Studnet Instance()
    25         {
    26             //双if加lock
    27             if (_instance == null)
    28             {
    29                 lock (_SingleLock)
    30                 {
    31                     if (_instance == null)
    32                     {
    33                         _instance = new Studnet();
    34                     }
    35                 }
    36             }
    37             return _instance;
    38         }
    39 
    40 
    41         //单例第二种写法
    42 
    43         /// <summary>
    44         /// 创建一个静态构造函数
    45         /// </summary>
    46         /// 静态构造函数在调用该类之前被CLR自动初始化,常驻内存,不会被GC回收
    47         static Studnet()
    48         {
    49             _instance = new Studnet();
    50         }
    51         public static Studnet stuInstance()
    52         {
    53             return _instance;
    54         }
    55 
    56 
    57 
    58         //单例第三种写法
    59 
    60         //创建一个私有的静态变量,当调用该类之前创建并且只会被初始化一次
    61         private static Studnet stu = new Studnet();
    62 
    63         public static Studnet InstanceSingle()
    64         {
    65             return stu;
    66         }
    67 
    68     }
    69 }
    世界上最可怕事情是比我们优秀的人比我们还努力
  • 相关阅读:
    1074. Reversing Linked List (25)
    1056. Mice and Rice (25)
    1051. Pop Sequence (25)
    1001. A+B Format (20)
    1048. 数字加密(20)
    1073. Scientific Notation (20)
    1061. Dating (20)
    1009. 说反话 (20)
    MyBatis学习总结(8)——Mybatis3.x与Spring4.x整合
    MyBatis学习总结(8)——Mybatis3.x与Spring4.x整合
  • 原文地址:https://www.cnblogs.com/AlexOneBlogs/p/7309557.html
Copyright © 2011-2022 走看看