asp.net 工厂模式 各层 代码 用处

补充:面向接口编程和面向对象编程并不是平级的,它并不是比面向对象编程更先进的一种独立的编程思

想,而是附属于面向对象思想体系,属于其一部分。或者说,它是面向对象编程体系中的思想精髓之一。

分层是为了实现“高内聚,低耦合”。采用“分而治之”的思想,把问题划分开来各个解决,易于控制,延展和分配资源。

注:System.Collections.Generic 命名空间包含定义泛型集合的接口和类,泛型集合允许用户创建强类型集合,它能提供比非泛型强类型集合更好的类型安全性和性能。
System.Reflection 命名空间包含提供加载类型、方法和字段的有组织的视图的类和接口,具有动态创建和调用类型的功能。

web界面层调用BLL业务层,BLL通过抽象工厂DALFactory动态生成继承了IDAL的数据库操作层实例,以进行对数据库的各项操作。
DALFactory这层主要是根据web配置,通过反射动态生成IDAL实例,方便BLL层调用。



SQLServerDAL:继承接口,调用DBUtility内方法
using System.Text;
using System;
using System.Data;
using System.Web;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.SqlClient;
using IDAL;
using Model;
using DBUtility;


namespace SQLServerDAL
{
   public class Bname:IBname
    {
       public IList<BnameInfo> GetBnames()//添加含参或不含参自定义泛型,集合等方法
        {
            SqlHelper objSqlHelper = new SqlHelper();//实例化DBUtility里的SqlHelper 
            List<BnameInfo> bns = new List<BnameInfo>();
            SqlDataReader reader = objSqlHelper.GetDataReader("select * from tb_bname order by name");//调用SqlHelper .GetDataReader方法
            while (reader.Read())
            {
                BnameInfo item = GetBnameByID(reader.GetInt32(reader.GetOrdinal("ID")));
                 bns.Add(item);
            }
            reader.Close();
            objSqlHelper.GetClose();
            return bns;
        }
}
IDAL:SQLServerDAL找到对应接口
using System;
using System.Collections.Generic;
using System.Text;
using Model;
namespace IDAL
{
    public interface IBname
    {
         IList<BnameInfo> GetBnames();
    }
}

BLL:构造方法,返回接口,在BLL调用DAL的时候,通过一个反射工厂生成DAL实例

以前BLL直接调用DAL就好了,但现在BLL却调用了IDAL,IDAL只是一个接口层,里面封状了要完成的一些业务逻辑,而具体的实现则交给DAL去实现,然后借助于工厂模式DALFactory和映射完成IDAL层中类的实例化。

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using Model;
using System.ComponentModel;
using IDAL;
using DALFactory;
namespace BLL
{
    [DataObjectAttribute]
    public class Bname
    {
        private static readonly IBname es = DataAccess.CreateBname();
/*方法二:抽象,封装private static readonly IBname es = DALFactory.ObjDataAccess<IBname>.Get();*/
        public static IList<BnamesInfo> GetBnames()
        {
            return es.GetBnames();
        }
}
DALFactory:反射,动态创建加载程序集,得到程序集中的属性和方法。
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Configuration;
using IDAL;
namespace DALFactory
{
    /// <summary>
    /// 抽象工厂
    /// </summary>
    public class DataAccess               
    {
        // 查找程序集
        private static readonly string path = ConfigurationManager.AppSettings["WebDAL"];//从web.config里获得数据层的程序集名
// Web.config 需要加入配置:(利用工厂模式+反射机制+缓存机制,实现动态创建不同的数据层对象接口


)
  /// <appSettings>
  /// <add key="DAL" value="System.SQLServerDAL" /> (这里的命名空间根据实际情况更改为自己项目的命名空间)
  /// </appSettings>
  /// 可以把所有DAL类的创建放在这个DataAccess类里
        private DataAccess() { }
        public static IBname CreateBname()
        {
            string className = path + ".Bname";//程序集+类名,得到类的类型全名

            return (IBname )Assembly.Load(path).CreateInstance(className);// CreateInstance(className)这里的className其实是需要反射的类型全名

//(包括命名空间的全路径)。 所以,尽量让程序集名称和命名空间一致,这样的得到的类型全名=程序集名称+类名。

//否则,你需要把CacheKey换成实际的类型全名。
        }


//封装接口T
    public sealed class ObjDataAccess<T>
    {
        private static readonly string path = ConfigurationManager.AppSettings["WebDAL"];
        public static T Get()
        {
            string className = path + "." + typeof(T).Name.Substring(1);
            object objType = Assembly.Load(path).CreateInstance(className);
            return (T)objType;
        }
    }
}
DBUtility:封装的数据库操作
using System.Data.OleDb;
using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web;
namespace DBUtility
{
    public class SqlHelper    
   {
        public static string constring = ConfigurationManager.ConnectionStrings


["ConnectionToBJ"].ConnectionString;     
        //打开数据库连接
        public void Open()
        {
            if (cnn == null)
            {
                string strSqlSqlConn = ConfigurationManager.ConnectionStrings


["ConnectionToBJ"].ConnectionString;
                cnn = new SqlConnection(strSqlSqlConn);
            }
            if (cnn.State == ConnectionState.Closed)
            {
                try
                {
                    cnn.Open();
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
            }
        }
public void close(){}
 public SqlDataReader ExecuteReader(string query){}
public static DataTable ExecuteDataTable(string sql){}
 public static DataSet ExecuteDataSet(string sql){}
public static bool ExecuteNonqueryBool(string sql){}
public static bool Exists(string sql){}
public SqlDataReader GetDataReader(string strSql){}
 public SqlConnection GetConnect(){}
public void GetClose(){}
public DataView CreateDataView(string strSql){} 
public bool ExecSql(string strSql){}//根据Sql语句,实现增、删、改操作
private void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, 


CommandType cmdType, string cmdText, SqlParameter[] cmdParms){}
}
  
封装一下factory
using System.Reflection;
using System.Web;
using System.Web.Caching;
using System.Configuration;


 namespace EHRExcelReprot.DALFactory
{
     public sealed class ObjDataAccess<T>
     {
         //获取web.confg文件配置信息
          private static readonly string path = ConfigurationManager.AppSettings


["ExcelReportDAL"];
         public static T Get()
         {
            //注意:这里一定要确保这样一个命名规则:接口类名称只比继承它的类名称前面多一个‘I’字母
             //如:接口类名:IUser,继承它的类:User
              string CacheKey = path + "." + typeof(T).Name.Substring(1);
             object objType = DataCache.GetCache(CacheKey);//从缓存读取
              if (objType == null)
             {
                try
               {
                     objType = Assembly.Load(path).CreateInstance(CacheKey);//反射创建
                     DataCache.SetCache(CacheKey, objType);// 写入缓存
                 }
                 catch
                 { }
             }
             return (T)objType;
         }
     }
     /// <summary>
     /// 缓存操作类
     /// </summary>
    public class DataCache
     {
        public static object GetCache(string CacheKey)
         {
           Cache objCache = HttpRuntime.Cache;
            return objCache[CacheKey];
         }


        public static void SetCache(string CacheKey, object objObject)
         {
            Cache objCache = HttpRuntime.Cache;
            objCache.Insert(CacheKey, objObject);
         }
     }
 }

Model:设置字段属性
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;


namespace MyCrm.Model
{
    public class HcInfo
    {
        private int intId;
        public int id
        { get; set; }
        private string strName;
        public string name
        { get; set; }
        private string strAddress;
        public string address
        { get; set; }
        private string strCode;
        public string code
        { get; set; }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值