PetShop是如何兼容数据库的

数据库的移植通常会带来高额的代价。这一点我深有体会。代价的大小就要看程序的架构写的怎么样了 . 去年把一个项目从 MySQL 移至到 Oracle, 整个程序里里外外都做了修修补补,大概花了两个月。

如果做到少修改,甚至不修改代码的前提下,对数据库的兼容无疑是一件非常好的事情,

PetShop 很好的做到了这一点

要兼容多种数据库,首先要实现多态。 SQLServerDAL 和 OracleDAL 都实现了 IDAL 里所有接口的方法,实现了多态性。

FactoryDAL 用来创建 DAL 对象 ,

public static PetShop.IDAL.IAccount Create()

{

/// Look up the DAL implementation we should be using

string path = System.Configuration.ConfigurationSettings.AppSettings["WebDAL"];

string className = path + ".Account";

// Using the evidence given in the config file load the appropriate assembly and class

return (PetShop.IDAL.IAccount) Assembly.Load(path).CreateInstance(className);

}

如上: 创建Account, 首先获取Web.config 中的WebDAL的值。

< add key ="WebDAL" value ="PetShop.SQLServerDAL" />

Web.Config里 ” WebDAL ” 的值是 PetShop.SQLServerDAL,该值决定了所要创建的DAL的路径。

然后再用 Assembly.CreateInstance() 创建 DAL 实例 .

若要使用 Oracle 数据库 , 只要把

< add key ="WebDAL" value ="PetShop.SQLServerDAL" />和

< add key ="OrdersDAL" value ="PetShop.SQLServerDAL" />

中的 PetShop.SqlServerDAL 改为 PetShop.OracleDAL 就可以了。

而在 BLL 中,它不需要知道你使用那个数据库。只是通过如下语句得到对象。

// Get an instance of the account DAL using the DALFactory

IAccount dal = PetShop.DALFactory.Account.Create();

无论使用什么数据库, BLL 模块都不需要修改。

扩展性 : 若要兼容 MySQL 数据库改怎么办 ?

写一个 MySQLDAL 模块,实现 IDAL 里所有接口的方法。 再修改 Web.config 中的值即可。

PetShop 提供了良好的可扩展性 , 封闭了业务层的修改。很好的满足了 OCP ( 开放-封闭原则 ).

Published At
Categories with Web编程
Tagged with
comments powered by Disqus