通常我們在做VS多層架構的開發中都回用到資料訪問的工廠 ,以此來產生資料訪問實現層中具體類的對象。
如下面例子:
using System.Configuration;
using System.Reflection;
using IDAL;
namespace DALFactory
{
/// <summary>
/// 抽象原廠模式建立DAL-(利用原廠模式+反射機制+緩衝機制,實現動態建立不同的資料層對象介面) 。
/// DataCache類在匯出代碼的檔案夾裡
/// 可以把所有DAL類的建立放在這個DataAccess類裡
/// </summary>
/// <example>web.config 需要加入配置:
/// </example>
public sealed class DataAccess
{
private static readonly string path = ConfigurationSettings.AppSettings["DAL"];
/// <summary>
/// 建立對象或從緩衝擷取
/// </summary>
public static object CreateObject(string CacheKey)
{
object objType = DataCache.GetCache(CacheKey);//從緩衝讀取
if (objType == null)
{
objType = Assembly.Load(path).CreateInstance(CacheKey+"DAL");//反射建立
DataCache.SetCache(CacheKey, objType);// 寫入緩衝
}
return objType;
}
/// <summary>
/// 建立使用者資料層介面
/// </summary>
/// <returns>IRegUser介面</returns>
public static IRegUser CreateRegUser()
{
string CacheKey = path + ".RegUser";
object objtype = CreateObject(CacheKey);
return (IRegUser)objtype;
}
/// <summary>
/// 建立使用者角色資料層介面
/// </summary>
/// <returns>IRole介面</returns>
public static IRole CreateRole()
{
string CacheKey = path + ".Role";
object objtype = CreateObject(CacheKey);
return (IRole)objtype;
}
}
}
這中做法就會有這樣一個問題,IDAL 中有多少個介面,我們必須在此類中寫下多少對應的靜態方法!有沒有更好的解決辦法呢?答案是肯定的!我們可以利用dotNet 2.0中的泛型!
修改代碼如下:
/// <summary>
/// 抽象原廠模式建立DAL-(利用原廠模式+泛型機制+反射機制+緩衝機制,實現動態建立不同的資料層對象介面) 。
/// 可以在這個DataAccess類裡建立所有DAL類
/// </summary>
public sealed class DataAccess
{
/// <summary>
/// 資料訪問的具體實現
/// </summary>
private static readonly string path = ConfigurationManager.AppSettings["DAL"];
/// <summary>
/// 採用泛型建立對象或從緩衝擷取
/// </summary>
/// <typeparam name="T">資料類型</typeparam>
/// <returns>確定類型的對象</returns>
public static T CreateObject<T>()
{
// 此處可採用XML,把對應關係做的更加靈活
string typeName = "." + typeof(T).Name.Substring(1) + "DAL";
object obj;
// 從緩衝中讀取資料
obj = DataCache.GetCache(typeName);
// 建立新的執行個體
if (obj == null)
{
obj = Assembly.Load(path).CreateInstance(path + typeName); // 反射建立
DataCache.SetCache(typeName, obj); // 放入緩衝中
}
return (T)obj;
}
}
OK!問題解決了!