第四回 基础才是重中之重~你是否真正理解static对象

我们挂在嘴过的一句话就是“static是静态对象,在类第一次被使用,或者第一次被实例化时执行“,但是你是否真正理解这句话,或者说

你是否有对这句话进行一个实际的验证,如果没有,那我来带您完成这次旅行吧!

首先有一张表,不会经常发生变化,比如分类表,他是一种树型结构表,结构可能是这样

  

复制代码
 1  /// <summary>
 2     /// 分类表       
 3     /// </summary>
 4     public partial class Common_Category : IDataEntity
 5     {
 6         //初始字段
 7         #region original field
 8 
 9         /// <summary>
10         /// ID
11         /// </summary>
12         public Int32 ID { get; set; }
13 
14         /// <summary>
15         /// 上级ID
16         /// </summary>
17         public Int32 ParentID { get; set; }
18  
19 
20         /// <summary>
21         /// 名称
22         /// </summary>
23         public String Name { get; set; }
复制代码

首先,它在程序中会经常被调用,也就是说,会经常访问这张数据表,由于它的内容基本不变,所以,我想到了static对象,下面我用static对象来完成这个需求

  

复制代码
 1   /// <summary>
 2         /// 得到静态对象(一般表数据不发生变)
 3         /// </summary>
 4         /// <returns></returns>
 5         public static IList<Common_Category> GetCommon_CategoryModel
 6         {
 7             get
 8             {
 9                 return new LinqDBDataContext().Common_Category.ToList();
10             }
11         }
复制代码

这样,可以完成我们的需求,这种设计在单机调试时没有任何问题,但发布后,在IIS里访问时,它的对象虽然创建了一次,但没是刷新一次

就连接一次数据库,没有解决我们的问题,之后,有了新的想法:

单件,对单件模式,每个对象有且只有一个实例出现,有两个方式的单件,线程安全的和不安全的,呵呵,都拿出来看看:

复制代码
 1 /// <summary>
 2     /// 线程安全的单件模式
 3     /// </summary>
 4     public sealed class StaticCustomer
 5     {
 6         private static volatile IList<Customer> instance = null;
 7         // Lock对象,线程安全所用
 8         private static object syncRoot = new Object();
 9 
10         private StaticCustomer() { }
11 
12         public static IList<Customer> Instance
13         {
14             get
15             {
16                 if (instance == null)
17                 {
18                     lock (syncRoot)
19                     {
20                         if (instance == null)
21                             instance = new LinqDBDataContext().Customer.ToList();
22                     }
23                 }
24 
25                 return instance;
26             }
27         }
28     }
29 
30     /// <summary>
31     /// 简单的模式,没有考虑线程问题
32     /// </summary>
33     public sealed class SingtonCustomer
34     {
35         private static IList<Customer> instance = null;
36         private SingtonCustomer() { }
37         public static IList<Customer> Instance
38         {
39             get
40             {
41                 if (instance == null)
42                 {
43                     instance = new LinqDBDataContext().Customer.ToList();
44                 }
45                 return instance;
46             }
47         }
48     }
复制代码

建议使用线程安全的单件,通过测试,没有问题。

原文地址:https://www.cnblogs.com/ywsoftware/p/3068440.html