zoukankan      html  css  js  c++  java
  • 单例

     1 /// <summary>
     2     /// 单线程单例
     3     /// </summary>
     4     public class SingleThreadSingleton
     5     {
     6         //保存实例容器
     7         private static SingleThreadSingleton instance = null;
     8         private SingleThreadSingleton() { }
     9         //通过属性暴露静态实例
    10         public static SingleThreadSingleton Instance
    11         {
    12             get 
    13             {
    14                 //多线程下此处会出现竞争导致的错误,保持不了一直是一个实例
    15                 if (instance == null)
    16                 {
    17                     instance = new SingleThreadSingleton();
    18                 }
    19                 return instance;
    20             }
    21         }
    22     }
    23 
    24     /// <summary>
    25     /// 多线程下单例
    26     /// </summary>
    27     public class MultiThreadSingleton
    28     {
    29         //volatile 保证严格意义的多线程编译器在代码编译时对指令不进行微调。
    30         private static volatile MultiThreadSingleton instance = null;
    31         //防止竞争资源导致的实例不唯一
    32         private static object lockHelper = new object();
    33         private MultiThreadSingleton() { }
    34         public static MultiThreadSingleton Instance
    35         {
    36             get 
    37             {
    38                 if (instance == null)
    39                 {
    40                     lock (lockHelper)
    41                     {
    42                         if (instance == null)
    43                         {
    44                             instance = new MultiThreadSingleton();
    45                         }
    46 
    47                     }
    48                 }
    49                 return instance;
    50             }
    51         }
    52     }
    53 
    54     //静态单例
    55     public class StaticSingleton
    56     {
    57         public static readonly StaticSingleton instance = new StaticSingleton();
    58         private StaticSingleton() { }
    59     }

    ps:

    单例即

      保持同一个实例,所以选私有静态。

      属性暴露实例

      私有构造函数 保证外部不能实例化

      -------------------

      多线程加锁

      保证实例唯一

      ------------------ 

  • 相关阅读:
    golang中,new和make的区别
    k8s客户端库
    k8s 拉取私有镜像
    kubernetes-client / python
    k8s集群外go客户端示例
    K8s获取NodePort
    KUBERNETES中的服务发现机制与方式
    Rancher容器目录持久化
    rancher k8s 实现pod弹性伸缩
    在Terminal里,使用Shift+Insert来代替鼠标右键来进行粘贴操作
  • 原文地址:https://www.cnblogs.com/weiruanojbk/p/14509804.html
Copyright © 2011-2022 走看看