• PetShop是如何兼容数据库的.NET教程,数据库应用


    数据库的移植通常会带来高额的代价。这一点我深有体会。代价的大小就要看程序的架构写的怎么样了. 去年把一个项目从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(开放-封闭原则).
  • 相关阅读:
    c#一次性队列
    WinDbg
    async/wait
    JS 同步任务和异步任务
    VS Code格式设置
    ES6模块化导入导出
    Promise
    Spring配置
    AtCoder Beginner Contest 241 F Skate(bfs、STL)
    牛客寒假算法基础集训营6 G 迷宫2(01bfs)
  • 原文地址:https://www.cnblogs.com/cxd4321/p/1333429.html
Copyright © 2020-2023  润新知