一、什么是简单工厂
它又被称为静态工厂,是抽象工厂的扩展。
二、简单的一个C#例子
通过配置文件来控制打印报表的选择
- App.config 来配置选择什么报表
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<appSettings >
<add key="ReportType" value="Excel"/>
</appSettings>
</configuration>
- Factory.cs通过反射生成对应的报表对象
using System;
using System.Configuration;
using System.Reflection;
using Product;
namespace ReportFactory
{
public class Factory
{
private static IReport objReport = null;
private static string reportType = ConfigurationManager.AppSettings["ReportType"].ToString();
public static IReport CreateReport()
{
try
{
objReport = (IReport)Assembly.LoadFrom("Product.dll").CreateInstance("Product." + reportType);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
return objReport;
}
}
}
- 高层模块通过时间调用工厂的静态方法
private void btnPrint_Click(object sender, EventArgs e)
{
IReport objReport = Factory.CreateReport();
if (objReport == null)
{
MessageBox.Show("工厂创建对象失败!");
}
else
{
MessageBox.Show(objReport.Print());
}
}
这样当需要添加新的打印报表类型时,只需要扩展一个新的product实现类,修改配置文件就能达到更换新报表的打印。