首页 > 开发 > 综合 > 正文

用C#实现的数据库抽象工厂(一)

2024-07-21 02:19:45
字体:
来源:转载
供稿:网友


收集最实用的网页特效代码!

用c#实现的数据库抽象工厂(一)

最近学习了一下设计模式,便尝试用c#对数据库的访问操作采用抽象工厂的模式实现一下,其中与标准的模式略有不同,加入了一些自己的想法,希望大家批评指正,代码共分为6个类:

(1)abstractdbfactory.cs

using system;
using system.data;

namespace dbservice
{
/// <summary>
/// 数据库抽象工厂接口
/// </summary>
public interface abstractdbfactory
{
/// <summary>
/// 建立默认连接
/// </summary>
/// <returns>数据库连接</returns>
idbconnection createconnection();

/// <summary>
/// 根据连接字符串建立connection对象
/// </summary>
/// <param name="strconn">连接字符串</param>
/// <returns>connection对象</returns>
idbconnection createconnection(string strconn);

/// <summary>
/// 建立command对象
/// </summary>
/// <returns>command对象</returns>
idbcommand createcommand();

/// <summary>
/// 建立dataadapter对象
/// </summary>
/// <returns>dataadapter对象</returns>
idbdataadapter createdataadapter();

/// <summary>
/// 根据connection建立transaction
/// </summary>
/// <param name="mydbconnection">connection对象</param>
/// <returns>transaction对象</returns>
idbtransaction createtransaction(idbconnection mydbconnection);

/// <summary>
/// 根据command建立datareader
/// </summary>
/// <param name="mydbcommand">command对象</param>
/// <returns>datareader对象</returns>
idatareader createdatareader(idbcommand mydbcommand);

/// <summary>
/// 获得连接字符串
/// </summary>
/// <returns>连接字符串</returns>
string getconnectionstring();
}
}


(2)factory.cs

using system;
using system.configuration;

namespace dbservice
{
/// <summary>
/// factory类
/// </summary>
public sealed class factory
{
private static volatile factory singlefactory = null;
private static object syncobj = new object();
/// <summary>
/// factory类构造函数
/// </summary>
private factory()
{
}

/// <summary>
/// 获得factory类的实例
/// </summary>
/// <returns>factory类实例</returns>
public static factory getinstance()
{
if(singlefactory == null)
{
lock(syncobj)
{
if(singlefactory == null)
{
singlefactory = new factory();
}
}
}
return singlefactory;
}

/// <summary>
/// 建立factory类实例
/// </summary>
/// <returns>factory类实例</returns>
public abstractdbfactory createinstance()
{
abstractdbfactory abstractdbfactory = null;
switch(configurationsettings.appsettings["databasetype"].tolower())
{
case "sqlserver":
{
abstractdbfactory = new sqlfactory();
break;
}
case "oledb":
{
abstractdbfactory = new oledbfactory();
break;
}
case "odbc":
{
abstractdbfactory = new odbcfactory();
break;
}
}
return abstractdbfactory;
}
}
}


待续......

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表