通用且可扩展的数据访问工厂






2.67/5 (3投票s)
2004年7月18日
2分钟阅读

41303

459
使用和扩展数据访问类,并使用工厂和XML配置文件进行运行时选择和实例化。
引言
本文档描述了如何使用数据访问工厂来创建运行时对象,这些对象连接到 Oracle 或 SQL Server 并进行查询。 演示项目展示了如何在不更改任何代码的情况下更改数据提供程序。 只要继承自抽象类DataAccessBase
,工厂类就能够创建您指定的任何类型的对象。 工厂从开发人员指定的 XML 文件中获取有关要创建的对象类型的信息,该文件通常位于项目 *bin* 目录(对于 Window Forms 项目)或虚拟目录(对于 Web 应用程序)中。 目前,该应用程序包含DataAccessBase
类的两个派生类:OracleDAO
和SQLServerDAO
。 可以轻松地修改该程序集以包含其他数据提供程序,例如 Microsoft Access。
核心数据访问工厂与数据访问类(DAO 类)一起在名为 DAL(数据访问库)的程序集中实现。(提到的 DAO 类不应与早期 VB 6 命名法中引用的RecordSet
和其他对象混淆。它们是不相关的。)通过点击上面的链接,可以从 zip 文件中获取演示项目。该示例演示了如何从控制台应用程序中使用工厂 - 使用演示快速学习如何使用工厂。
数据访问工厂程序集对于想要编写业务逻辑或表示逻辑而无需关心将使用哪个数据库供应商的开发人员非常有用。如果没有这种类型的逻辑,业务逻辑代码和表示逻辑代码将很难与用于访问数据库的对象分离。
此外,数据访问工厂程序集的客户端可以使用多个数据源。
背景
我查看了文章数据访问和事务处理框架,希望用它来替代我开发的东西,但最终没有使用它,因为它使用了 SQL 语句以及数据库对象实例化指令,这些都包含在配置文件中。 我不想那样。 此外,我希望我的数据库对象实例化设置与该文章中的不同。 但是,当前项目是作为工厂实现的,引用文章中的项目也是如此。 如果您感兴趣,您可能需要考虑评估该代码以作为使用此代码的替代方案。
使用代码
下面的代码块显示了示例应用程序如何使用DataAccessFactory
和DataAccess
类。
//Define (declare and set memory aside) a factory object
// that takes care of creating and returning
// a reference to the correct data access object type.
DataAccessFactory myDBFactory = new DataAccessFactory();
//Declare a variable capable of being any DAO object type
DataAccessBase myDBObj;
//Define a object (locally defined) that will help
// with the dirty chores of setting properties of
// the factory. This object is not necessary, but just
// helps abstract out unnecessary details used in this
// particular test.
try
{
factoryProperties = new factoryHelper();
myDBFactory.ObjectTypeToCreate = factoryProperties.getDaoObjectType;
myDBFactory.ObjectSetupIndex = factoryProperties.getIndex;
myDBFactory.ConfigFileName = factoryProperties.getXMLFileName;
}
catch (Exception e)
{
Console.WriteLine ("Problem in Factory Helper");
Console.WriteLine ("Message: " + e.Message);
Console.WriteLine ("Source: " + e.Source);
return;
}
try
{
//Use the factory to instantiate the appropriate type of
// DAO object. Assign the object to the base class object.
myDBObj = myDBFactory.CreateVendorDAO();
//Use the DAO object to generate a return a dataset based on
// a user supplied query.
string strSQL = "select * from customers";
DataSet resultsDS = myDBObj.getDataSet(strSQL);
}
catch (Exception e)
{
//Catch and report any problems.
Console.WriteLine ("Found prblem.");
Console.WriteLine("Error message: [{0}]", e.Message);
Console.WriteLine("Source [{0}]", e.Source);
}