当你需要什么,只需要传入一个正确的参数,就可以获取你所需要的对象,而无须知道其创建的细节。
接下来就用console app project 来实现简单工厂
第一步,这里因为需要用到多态来实现,无非就是abstract 或 interface,我们这里就用interface吧。
定义interface:
public interface IChart
{
void Display();
}
然后我们把这个接口实现:
实现1:
public class HistogramChart : IChart
{
public HistogramChart()
{
Console.WriteLine("create new histogram chart!");
}
public void Display()
{
Console.WriteLine("show chart!");
}
}
实现2:
public class LineChart:IChart
{
public LineChart()
{
Console.WriteLine("create line chart!");
}
public void Display()
{
Console.WriteLine("show line chart!");
}
}
实现3:
public class PieChart :IChart
{
public PieChart()
{
Console.WriteLine("create pie chart!");
}
public void Display()
{
Console.WriteLine("show pie chart!");
}
}
接下来我们实现Factory:
public static IChart GetChart(string type)
{
IChart chart = null;
if (type.Equals("histogram"))
{
chart = new HistogramChart();
Console.WriteLine("histogram chart init!");
}
else if (type.Equals("pie"))
{
chart = new PieChart();
Console.WriteLine("pie chart init!");
}
else if (type.Equals("line"))
{
chart = new LineChart();
Console.WriteLine("line chart init!");
}
return chart;
}
实现工厂需要的输入参数type:
工厂里具体走哪个实现,需要通过判断这个参数来决定,也是简单工厂工作的必要条件。
public static string GetConfig()
{
XmlDocument doc = new XmlDocument();
doc.Load(@"Config.xml");
XmlNode root = doc.SelectSingleNode("config");
return root.FirstChild.InnerText;
}
这里用到了xml config :
<?xml version="1.0" encoding="utf-8" ?>
<config>
<chartType>histogram</chartType>
</config>
最后一步run:
class Program
{
static void Main(string[] args)
{
//读取配置
var type = ChartFactory.GetConfig();
//调用工厂
IChart chart = ChartFactory.GetChart(type);
//显现
chart.Display();
}
}
结果如下:
这里打印出来第一个实现里的内容。