PetShop是如何兼容數(shù)據(jù)庫(kù)的
2024-07-21 02:23:34
供稿:網(wǎng)友
數(shù)據(jù)庫(kù)的移植通常會(huì)帶來(lái)高額的代價(jià)。這一點(diǎn)我深有體會(huì)。代價(jià)的大小就要看程序的架構(gòu)寫(xiě)的怎么樣了. 去年把一個(gè)項(xiàng)目從mysql移至到oracle, 整個(gè)程序里里外外都做了修修補(bǔ)補(bǔ),大概花了兩個(gè)月。
如果做到少修改,甚至不修改代碼的前提下,對(duì)數(shù)據(jù)庫(kù)的兼容無(wú)疑是一件非常好的事情,
petshop很好的做到了這一點(diǎn)
要兼容多種數(shù)據(jù)庫(kù),首先要實(shí)現(xiàn)多態(tài)。sqlserverdal和oracledal都實(shí)現(xiàn)了idal里所有接口的方法,實(shí)現(xiàn)了多態(tài)性。
factorydal用來(lái)創(chuàng)建dal對(duì)象,
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);
}
如上:創(chuàng)建account, 首先獲取web.config 中的webdal的值。
<add key="webdal" value="petshop.sqlserverdal" />
web.config里”webdal”的值是petshop.sqlserverdal,該值決定了所要?jiǎng)?chuàng)建的dal的路徑。
然后再用assembly.createinstance()創(chuàng)建dal實(shí)例.
若要使用oracle數(shù)據(jù)庫(kù), 只要把
<add key="webdal" value="petshop.sqlserverdal" />和
<add key="ordersdal" value="petshop.sqlserverdal" />
中的petshop.sqlserverdal改為petshop.oracledal就可以了。
而在bll中,它不需要知道你使用那個(gè)數(shù)據(jù)庫(kù)。只是通過(guò)如下語(yǔ)句得到對(duì)象。
// get an instance of the account dal using the dalfactory
iaccount dal = petshop.dalfactory.account.create();
無(wú)論使用什么數(shù)據(jù)庫(kù),bll模塊都不需要修改。
擴(kuò)展性: 若要兼容mysql數(shù)據(jù)庫(kù)改怎么辦?
寫(xiě)一個(gè)mysqldal模塊,實(shí)現(xiàn)idal里所有接口的方法。 再修改web.config中的值即可。
petshop提供了良好的可擴(kuò)展性, 封閉了業(yè)務(wù)層的修改。很好的滿足了ocp(開(kāi)放-封閉原則).
中國(guó)最大的web開(kāi)發(fā)資源網(wǎng)站及技術(shù)社區(qū),