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

    简单的单例:

     1 public class Student
     2     {
     3         //1。私有静态变量
     4         private static Student stu = null;
     5 
     6         //2。私有化构造函数
     7         private Student()
     8         {
     9         }
    10 
    11         //3.提供一个静态方法让外部可以访问得到
    12         public static Student GetInstance()
    13         {
    14             if (stu == null)
    15             {
    16                 stu = new Student();
    17             }
    18             return stu;
    19         }
    20     }
    简单的单例模式,适用于非多线程

    多线程单例:

     1 //1。私有静态变量
     2         private static Student stu = null;
     3         private static object _lock = new object();
     4 
     5         //2。私有化构造函数
     6         private Student()
     7         {
     8         }
     9 
    10         //3.提供一个静态方法让外部可以访问得到
    11         public static Student GetInstance()
    12         {
    13             if (stu == null)
    14             {
    15                 lock (_lock)
    16                 {
    17                     if (stu==null)
    18                     {
    19                         stu = new Student();
    20                     }
    21                 }
    22                 
    23             }
    24             return stu;
    25         }
    适用于多线程的单例
  • 相关阅读:
    sh_09_字典的定义
    sh_08_格式化字符串
    sh_07_元组遍历
    sh_06_元组基本使用
    sh_05_列表遍历
    sh_04_列表排序
    sh_03_列表的数据统计
    图片懒加载
    UA池和ip代理池
    爬虫篇 --- 分布式爬虫
  • 原文地址:https://www.cnblogs.com/liyajie/p/3674910.html
Copyright © 2011-2022 走看看