2013-02-27 46 views
3

我已经继承了这段代码,并且出于某种原因,原作者确实非常喜欢静态只读引用。对服务类使用静态只读引用有什么问题吗?

我已经在下面列出了一般模式,什么后果不具有这些静态只读引用有哪些?

public class DbAccess 
{ 
    private static readonly ISomethingFactory = SomethingFactories.GetFactory("1"); 
    private static IThing1Dao Thing1Dao { get {return ISomethingFactory.Thing1Dao; }} 
    private static IThing2Dao Thing2Dao { get {return ISomethingFactory.Thing2Dao; }} 
} 

public class SomethingFactories 
{ 
    public static ISomethingFactory GetFactory(string key) 
    { 
     switch(key) 
     { 
     case "...": 
     return new SomeFactory(); 
     } 
    } 
}  

public class SomeFactory : ISomeFactory 
{  
    public IThing1Dao Thing1Dao 
    { 
     get { return new Thing1Dao(); } 
    } 
}  

public class SomeService : ISomeService 
{ 
    private static readonly IThing1Dao thing1Dao = DbAccess.Thing1Dao 
    private static readonly IThing2Dao thing2Dao = DbAccess.Thing2Dao 

    public Thing1Object1 GetObject1(int id) 
    { 
     return thing1Dao.GetObject1(id);  
    } 

    public Thing1Object2 GetObject2(int id) 
    { 
     return thing1Dao.GetObject2(id); 
    } 
} 

在.aspx页的使用是这样的:

public class MyBasePage : System.Web.UI.Page 
{ 
    protected static readonly SomeService someService = new SomeService();  
}  

public class SomeAspxPage : MyBasePage 
{ 
    void btnAddObject1(...) 
    { 
     Thing1Object1 obj1 = someService.GetObject(1); 
    } 
} 

回答

3

静态意味着ISomethingFactory只有一个实例存在,并且该实例可以通过类型来访问(未一个实例每个实例DbAccess)。

只读表示初始化后,该值不能被覆盖。

这是基于启动时刻数据进行初始化一个相当正常模式(例如,从app.config中的数据)。

3

Web应用程序是多线程的,所以静态成员的用途有限。

如果你有一个静态引用一个对象,该对象必须是线程安全的,或者你有使用它来进行同步,以便只有一个线程可以在任何时候使用它。

使静态参考只读意味着基准本身是线程安全的,因为一旦它的设置不能改变,但不会自动使对象,它的引用线程安全的。

+0

所以不会有任何锁定/序列化问题? – loyalflow 2013-02-28 15:40:11

+0

@ user1361315:任何锁定问题都取决于您所引用的对象以及您如何使用它。如果你想序列化属性,那么你有一个问题,因为静态成员不是序列化的,因为它们不是对象实例的一部分。 – Guffa 2013-02-28 15:44:00

相关问题