C#--简单工厂模式(使用 应用程序配置,反射,接口)
以下是学习笔记:
总体步骤:

1,添加接口 IDAL
namespace UseFactory
{
/// <summary>
/// 打印接口
/// </summary>
public interface IReport
{
void StartPrint();
}
}
2,添加接口类的实现类 DAL
namespace UseFactory
{
public class ExcelReport:IReport
{
public void StartPrint()
{
//在这里编写具体报表程序...
MessageBox.Show("正在调用Excel报表程序...!");
}
}
}
namespace UseFactory
{
public class WordRerport:IReport
{
public void StartPrint()
{
//在这里编写具体报表程序...
MessageBox.Show("正在使用Word报表程序...!");
}
}
}
3,添加工厂方法(没有使用反射)
namespace UseFactory
{
public static class Factory
{
//【1】定义接口变量
static IReport objIReport = null;
//【2】读取配置文件
static string reportType = ConfigurationManager.AppSettings["ReportType"].ToString();
//【3】实现接口类的对象
public static IReport ChooseReportType()
{
switch (reportType)
{
case "ExcelReport":
objIReport = new ExcelReport();
break;
case "WordReport":
objIReport = new WordRerport();
break;
case "OtherReport":
objIReport = new WordRerport();
break;
}
return objIReport;
}
}
}
3,添加工厂方法(使用反射)
//public static class Factory
//{
// //【1】定义接口变量
// static IReport objIReport = null;
// //【2】读取配置文件
// static string reportType = ConfigurationManager.AppSettings["ReportType"].ToString();
// //【3】使用反射创建实现接口类的对象
// public static IReport ChooseReportType()
// {
// objIReport = (IReport)Assembly.Load("UseFactory").CreateInstance("UseFactory." + reportType);
// //【4】返回接口变量
// return objIReport;
// }
//}
/// <summary>
/// 用接口实现的简单工厂
/// </summary>
public static class Factory
{
//【1】读取配置文件
static string reportType = ConfigurationManager.AppSettings["ReportType"].ToString();
//【2】使用反射创建实现接口类的对象并以接口类型返回
public static IReport ChooseReportType()
{
return (IReport)Assembly.Load("UseFactory").CreateInstance("UseFactory." + reportType);
}
}
4,添加配置文件
注意:App.config 配置文件中严格区分大小写
<?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings > <add key ="ReportType" value ="ExcelReport"/> </appSettings> </configuration>
5,调用工厂方法并实现功能
//动态调用报表打印程序
private void btnPrint_Click(object sender, EventArgs e)
{
//定义一个接口变量,并调用工厂类中的工厂方法
IReport objReport = Factory.ChooseReportType();
//调用接口的打印方法
objReport.StartPrint();
}

浙公网安备 33010602011771号