抽象工厂泛型解决方案

来源:互联网 发布:青岛seo排名优化公司 编辑:程序博客网 时间:2024/06/02 04:07


http://blog.163.com/xu_shuhao/blog/static/52577487201172210120776/


通常我们在做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;
}
}


0 0