Pab*_*tyk 16
它允许您使用DataReader而无需知道您正在使用哪种类型的DataReader(即SqlDataReader, OleDbDataReader, EtcDataReader
),因此如果有一天您想要更改使用它的datareader不会影响您的逻辑,换句话说它会为您提供抽象.例如 :
您可以使用
IDbCommand command = GiveMeSomeCommand();
IDataReader r = command.ExecuteReader();
Run Code Online (Sandbox Code Playgroud)
不知道您正在使用哪个提供商
有可能:
private static IDbCommand GiveMeSomeCommand()
{
return new OleDbCommand();
}
Run Code Online (Sandbox Code Playgroud)
或者它可以
private static IDbCommand GiveMeSomeCommand()
{
return new SqlCommand();
}
Run Code Online (Sandbox Code Playgroud)
管他呢.
编辑:
您也可以使用DBFactories.
DbProviderFactory factory = GiveMeSomeFactory();
IDbCommand command = factory.CreateCommand();
IDataReader r = command.ExecuteReader();
//and create more objects
IDataAdapter adapter = factory.CreateDataAdapter();
IDbConnection conn = factory.CreateConnection();
Run Code Online (Sandbox Code Playgroud)
然后在其他层创建您的提供程序
private DbProviderFactory GiveMeSomeFactory()
{
if(something)
return SqlClientFactory.Instance;
else if(somethingElse)
return OracleFactory.Instance;
else if(notThisAndNotThat)
return MySqlFactory.Instance;
else
return WhateverFactory.Instance;
}
Run Code Online (Sandbox Code Playgroud)
该方法将返回一个对象,该对象是一个类的实例,并且该类将支持该类IDataReader
.
关键是,对象的类型并不重要,只是该类实现了接口.
如果你正在开车,你不需要知道它是福特,还是丰田,你以同样的方式驾驶汽车.
驱动界面是一样的,一旦汽车支持界面,你就可以开车了.
同上IDataReader
,一旦返回的类支持接口,就可以使用它.
“返回一个接口”的真正含义是:
返回实现该接口的某个类的实例
在这种情况下,它返回一个与SqlDataReader
对象非常相似的对象,该对象允许您执行类似的方法Read()
并实现IDisposable
和IDataRecord
接口。