实战才是王道:工厂模式、三层架构、反射、多数据库问题

无废话,先看结构图:

核心代码:

public interface IField
    {
        /// <summary>
        /// //通过SQL得到数据列表
        /// </summary>
        /// <param name="cols">列名,可以用*</param>
        /// <param name="where">条件</param>
        /// <param name="orderBy">排序</param>
        /// <returns></returns>
        DataTable GetTable(string cols,string where,string orderBy);

        /// <summary>
        /// 根据主键删除数据
        /// </summary>
        /// <param name="appid"></param>
        /// <returns></returns>
        bool Delete(string appid);
    }
  public class FieldDal : DalBase, IField
    {
        public FieldDal()
        {
            this.TableName = "T_Fileds";
            this.PkField = "AppId";
        }
    }
public class FieldBll
    {
        private IField field = DalFactory.CreateField();//工厂创建对象
        public DataTable GetTable(string cols, string where, string orderBy)
        {
            return field.GetTable(cols, where, orderBy);
        }
        public bool Delete(string appid)
        {
            return field.Delete(appid);
        }
    }

工厂来了(使用反射):

 public sealed class DalFactory
    {
        private static readonly string DbType = ConfigurationManager.AppSettings["DbType"];
        private static readonly string AssemblyPath = ConfigurationManager.AppSettings["DAL"];
        public static IAdmin CreateAdmin()
        {
            IAdmin admin = (IAdmin)Assembly.Load(AssemblyPath).CreateInstance("Dals." + DbType + "Dal.AdminDal");
            return admin;
        }
        public static IField CreateField()
        {
            IField admin = (IField)Assembly.Load(AssemblyPath).CreateInstance("Dals." + DbType + "Dal.FieldDal");
            return admin;
        }
    }

现在客户说了,软件不错,我们准备升级MSSQL版本,怎么办呢?

我们要做的就是增加MSSQL数据库的DAL层,然后修改APP.CONFIG配置文件

 你可能只需要10分钟就能完成SQLITE到MSSQL数据库的升级,主要是修改一下不同数据库之间的语法问题。到这里你是否觉得很爽?

最后上代码,下载地址:https://files.cnblogs.com/AlexQY/WFA-Salary.zip,开发工具是VS2012+Sqlite,只提供雏形代码,项目还未完成,结构已经清晰了!

设计模式看了一堆,工厂模式看了一堆,有几个是真正理解并应用的?实战才是王道!

posted @ 2013-06-06 18:09  Alex_QY1987  阅读(2978)  评论(13编辑  收藏  举报