我自己总结的有的在博客园中借鉴不少,最后自己又整改了些东东。望各位前辈指点一二。
上面这个效果图就是我搭建的基础架构,
Common这个顾名思义就是帮助类。这里不在进行过多的讲解。
AbstractFactory这个类库是抽象该工厂,我想好多人都能猜到他是反射出下面的OrcalDAL和SQLDAL的,重要代码如下。
public static object CreateDAL(string assemblyPath, string objType, string type)
{
Type typ =typeof(T);
object cacheDao = DALCache.GetDao(typ.Name + type);
if (cacheDao == null)
{
if (type.Equals("SQL"))
{
cacheDao = Activator.CreateInstance<Poetry.SQLDAL.BaseService<T>>();
}
else
{
cacheDao = Assembly.Load(assemblyPath).CreateInstance(objType);
}
DALCache.InsertDaoCache(typ.Name, cacheDao);
}
return cacheDao;
}
看到里面我实用了,泛型+反射来映射出相应的数据访问层,我这里把他写死了,因为泛型加上+反射我没有找到更好的方式,如果有哪位前辈提出来,那更好了。那我这里无论外面你怎么添加数据访问层,那么我这里都不需要修改了。
IDAL类库,他是网站数据访问层的接口,你要是想更改个数据库,那你完全不用管,其他操作,那你只要实现我这个接口中的类库,那么就OK了。
同样接口类我也是用了,泛型类。
public interface IBaseDAL<T> where T : class, new()
{
/// <summary>
/// 取得实体集合
/// </summary>
/// <param name="conditions">条件</param>
/// <param name="pageSize">页面大小</param>
/// <param name="pageIndex">页码</param>
/// <param name="orderByStr">排序</param>
/// <param name="recCount">总数量</param>
/// <returns>实体集合</returns>
IList<T> GetList(string conditions, int pageSize, int pageIndex, string orderByStr, out int recCount);
}
而数据访问层怎么实现啊,居上可知道也是是用类的泛型动态传递实体类的。那我们就看下SQLDAL类库的代码吧。
public class BaseService<T> : IBaseDAL<T> where T : class, new()
{
/// <summary>
/// 取得实体集合
/// </summary>
/// <param name="conditions">条件</param>
/// <param name="pageSize">页面大小</param>
/// <param name="pageIndex">页码</param>
/// <param name="orderByStr">排序</param>
/// <param name="recCount">总数量</param>
/// <returns>实体集合</returns>
public IList<T> GetList(string conditions, int pageSize, int pageIndex, string orderByStr, out int recCount)
{
if (CheckKeyWord(orderByStr))
throw new Exception("conditions或者orderByStr包含有非法字符");
if (string.IsNullOrEmpty(orderByStr))
orderByStr = "ORDER BY ID DESC";
string sp = "SP_GetListByPage";
SqlParameter[] pc = new SqlParameter[]{
new SqlParameter("@tablename",typeof(T).Name),
new SqlParameter("@fields","*"),
new SqlParameter("@orderstr",orderByStr),
new SqlParameter("@wherestr",conditions),
new SqlParameter("@pagesize",pageSize),
new SqlParameter("@pageindex",pageIndex)};
IList<T> list;
using (SqlDataReader reader = DBHelper.GetReader(sp, CommandType.StoredProcedure, pc))
{
Materializer<T> m = new Materializer<T>();
list = m.Materialize(reader).ToList<T>();
if (list != null && reader.NextResult())
{
reader.Read();
recCount = Convert.ToInt32(reader["RecCount"]);
}
else
recCount = 0;
}
return list;
}
}
我在这里巧妙的运用了Materializer类库,他是一个我在网上找到的类库,他使我们开发程序是写过多的reader["field"],有的时候如果字段过多,会出现错误,从而影响开发进度。
同样的实现了OrcaleDAL类库,它里面结构和SQLDAL一样。第一幅图片里面可以体现出来,这里就不在过多讲解。
总之,就是泛型+反射+抽象工厂的实用。这是我自己写的,请各位多提意见。
由于项目正在进行,所以不能放过多的代码抱歉,但是我感觉我已经把精髓告之大家了。如果有什么建议或者需要,请留言啊。
如果转载请标注http://www.cnblogs.com/waters/archive/2012/07/24/2607290.html