利用抽象工厂设计模式构建多数据库操作Helper类库
为了软件产品可以满足多种数据库之间切换,而不必去修改数据库访问层的代码,我苦苦思索了许久,知道有一天我认识了抽象工厂设计模式,我突然豁然开朗。主要是利用了依赖倒置等编程思想。
首先我们定义数据库操作接口,因为是简单示例,所以写的有些简单。
public interface IDB
{
void RunSql(string sql);
DataSet GetDataSetBySql(string sql);
IDataReader GetDataReaderBySql(string sql);
}
Oledb类型数据库继承接口IDB,并实现接口具体操作:
public class OledbDataBase:IDB
{
public void RunSql(string sql)
{
throw new NotImplementedException();
}
public System.Data.DataSet GetDataSetBySql(string sql)
{
throw new NotImplementedException();
}
public System.Data.IDataReader GetDataReaderBySql(string sql)
{
throw new NotImplementedException();
}
}
SqlServer数据库继承接口IDB,并实现接口具体操作:
public class SqlServerDataBase:IDB
{
public void RunSql(string sql)
{
throw new NotImplementedException();
}
public System.Data.DataSet GetDataSetBySql(string sql)
{
throw new NotImplementedException();
}
public System.Data.IDataReader GetDataReaderBySql(string sql)
{
throw new NotImplementedException();
}
}
数据库工厂抽象类:
public abstract class FactoryDb
{
public abstract IDB GetDataBase();
}
实现Oledb类数据库工厂:
public class FactoryOledb:FactoryDb
{
private IDB _IDB;
public override IDB GetDataBase()
{
if (_IDB == null)
{
_IDB = new OledbDataBase();
}
return _IDB;
}
}
实现Sqlserver数据库工厂:
public class FactorySqlServer : FactoryDb
{
private IDB _IDB;
public override IDB GetDataBase()
{
if(_IDB==null)
{
_IDB = new SqlDataBase();
}
return _IDB;
}
}
根据数据库连接字符串获取相应数据库类型的操作类:
public class MyDataBase
{
private static DataType _DataType;
private static FactoryDb _Db;
public MyDataBase()
{ }
public static FactoryDb GetDb()
{
if (_DataType!=null)
{
_DataType = (DataType)Enum.Parse(typeof(DataType) , ConfigurationManager.ConnectionStrings["Connstring"].Name, true);
}
if(_Db==null)
{
switch (_DataType)
{
case DataType.Access:
_Db = new FactoryOledb();
break;
case DataType.SqlServer:
_Db =new FactorySqlServer();
break;
default:
_Db = null;
break;
}
}
return _Db;
}
}
希望各位朋友多多指点。

浙公网安备 33010602011771号