接口的使用:为了使系统能够在各种数据库上使用,必须建立一个统一的接口,采编业务逻辑层调用统一的接口,然后在数据访问层实现接口的定义。
namespace News.DataAccess //统一的接口 { public interface ISqlWraper { int GetItemCount(string Tablename); } }
然后在开发需要支持的数据库业务逻辑,不同的数据库,对应的业务逻辑也有所不同.我们需要把每个数据操作的方法都写好.
namespace News.DataAccess.Provider { public class SqlWraper:ISqlWraper { public int GetItemCount(string Tablename) { return 1; } } }
到了News.BLL层,当我们需要获取一张表的行数时,代码可以这样写:
在封装组件的时候,使用者在调用方法的时候,不需要知道究竟是用什么数据库对象,只需要调用接口来得到数据库处理方法就可以了namespace News.BLL{ public class FZCbBll { public int GetItemCount(string Tablename) { ISqlWraper sql; string sqltype = "SQL Server"; int nCount = 0; switch(sqltype) { case "SQL Server": sql = new SqlWraper(); nCount = sql.GetItemCount(Tablename); break; case "Sybase": sql = new SqlWraper(); nCount = sql.GetItemCount(Tablename); break; } return nCount; } } }