Home  >  Article  >  Database  >  PetShop是如何兼容不同数据库的

PetShop是如何兼容不同数据库的

WBOY
WBOYOriginal
2016-06-07 15:30:231060browse

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

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

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

PetShop很好的做到了这一点

要兼容多种数据库,首先要实现多态。SQLServerDALOracleDAL都实现了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的值。

addkey="WebDAL"value="PetShop.SQLServerDAL"/>

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

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

 

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

addkey="WebDAL"value="PetShop.SQLServerDAL"/>和

addkey="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(开放-封闭原则).

 
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn