PetShop是如何相容不同資料庫的

來源:互聯網
上載者:User

資料庫的移植通常會帶來高額的代價。這一點我深有體會。代價的大小就要看程式的架構寫的怎麼樣了. 去年把一個項目從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(開放-封閉原則).

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.