这样写c#单列模式属性是否可以?

问题描述:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
///<summary>
    /// 尝试单例模式
    /// </summary>
    public class Db
    {
        /// <summary>
        /// 需要的数据库
        /// </summary>
        private  static SPMEntities db = new SPMEntities();
        private static Db instance;
 
        /// <summary>
        /// 私有的构造方法
        /// </summary>
        private Db()
        {
             
        }
        public static void GetInstance()
        {
            if(instance==null)
            {
                instance = new Db();
            
        }
        public static SPMEntities GetDb()
        {
            GetInstance();
            return db ;
        }
 

 

解决方法:

public class Db 
{
   private static volatile Db instance = null;
   private static object lockHelper = new object();
   private  static SPMEntities db;
   private Db() 
   {     
      db=new SPMEntities(); 
   }
   public static Db GetDb(){
      if (instance == null)
      {
         lock (lockHelper)
        {
           instance =  new Db();
         }
      }
      return instance;
   }
}

Db _db=Db.GetDb();

解决方法2:

GetInstance想要初始化它。
获得这个参数啊。

问;这里static SPMEntities db = new SPMEntities();
如果我需要使用
db.Execute();
db.Add();db.update();
等方法的话
需要public么?
我的意思是db本身具有修改db的属性的方法。

 

解决方法3:

首先你获取的这个字段是静态的。
而你的类设计的是单例模式。你获取这个静态字段所用到的方法又是静态的。
这里就会出问题。
因为你的静态属性和你的类并没有绑定在一起。
也就是说你的单例模式内的所有公有属性都应该设计成实例属性和方法。
这样才能体现出单例模式的功能。

而且,一个类中的静态字段它的实例化就是在静态构造函数中进行的。
那么,当你调用这个静态方法时就默认初始化了,所以没必要在创建一个实例方法,然后在获取。

 

 

posted @ 2013-05-20 19:26  月夜风2013  阅读(184)  评论(0编辑  收藏  举报
合肥搬家公司 全自动包装机