先贴出一段简单代码,比如我们系统中一个简单的查询功能,代码如下:
SqlServerHelper sql = new SqlServerHelper();
sql.Query();
先要new SqlServerHelper实例 再调用其Query方法,这种一般情况下不会有什么问题,但是如果在做项目的时候,该程序要经常切换到不同的数据库来进行操作,在学习反射,接口,简单工厂这些东西之前,可能要通过反复的修改代码,重新编译发布才能实现。要重新修改成下面代码:
MySqlHelper sql = new MySqlHelper ();
sql.Query();
现在来看看我们如何用反射,接口,简单工厂这些东西来动态调用不同实例的Query方法呢?
先建一个IDBHelper类库,定义一个接口 ISqlHelper,定义一个Query方法。
public interface ISqlHelper
{
void Query();
}
然后建一个DBHelper类库,里面有两个操作不能数据库的类继承ISqlHelper接口,SqlServer,Mysql
public class MySqlHelper :ISqlHelper
{
public void Query()
{
Console.WriteLine("调用MySqlHelper类Query方法!");
}
}
public class SqlServerHelper :ISqlHelper
{
public void Query()
{
Console.WriteLine("调用SqlServerHelper类Query方法!");
}
}
最后创建一个简单工厂类
public class SimpleFactory
{
/// <summary>
/// 创建一个SqlHelper实列
/// </summary>
/// <returns></returns>
public static ISqlHelper GetSqlHelperInstance()
{
string assemblyName = System.Configuration.ConfigurationManager.AppSettings["DBHelperName"].Split(',')[1];
string typeName = System.Configuration.ConfigurationManager.AppSettings["DBHelperName"].Split(',')[0];
return Assembly.Load(assemblyName).CreateInstance(typeName) as ISqlHelper;
}
}
最后调用的时候,代码如下:
class Program
{
static void Main(string[] args)
{
SimpleFactory.GetSqlHelperInstance().Query();
Console.ReadLine();
}
}
app.config 配置文件代码如下:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="DBHelperName" value="DBHelper.MySqlHelper,DBHelper"></add>
</appSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
这样如果需要切换数据库,只需要改app.config 文件里面的代码即可,并不需要再去修改代码。
用Assembly类反射动态的创建实例,转化为对应的接口,然后在程序中直接调用此接口。