我已經繼承了這段代碼,並且出於某種原因,原作者確實非常喜歡靜態只讀引用。對服務類使用靜態只讀引用有什麼問題嗎?
我已經在下面列出了一般模式,什麼後果不具有這些靜態只讀引用有哪些?
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);
}
}
所以不會有任何鎖定/序列化問題? – loyalflow 2013-02-28 15:40:11
@ user1361315:任何鎖定問題都取決於您所引用的對象以及您如何使用它。如果你想序列化屬性,那麼你有一個問題,因爲靜態成員不是序列化的,因爲它們不是對象實例的一部分。 – Guffa 2013-02-28 15:44:00