标签:stat void uml类图 getchar 柱状图 版本 hba 控制台 不同
定义了一个创建对象的接口,由子类决定实例化哪一个对象,工厂方法让类把实例化推迟到子类。
案例:提供一个画图程序,支持柱状图和饼图,根据不同的用户类型(免费/付费),显示不同的图形版本,付费用户会得到更丰富的图形显示。
为了能够简单描述工厂方法模式,应用以控制台应用的形式编写
public interface IChartCreater
{
IChart GetChart(string type,string title);
}
public interface IChart
{
string Title { get; set; }
void GenerateChart();
}
public class BarChart : IChart
{
public string Title { get; set ; }
public BarChart(string title)
{
Title = title;
}
public void GenerateChart()
{
Console.WriteLine($"Drawing a Bar chart with title {Title}");
}
}
public class PieChart : IChart
{
public string Title { get; set; }
public PieChart(string title)
{
Title = title;
}
public void GenerateChart()
{
Console.WriteLine($"Drawing a Pie chart with title {Title}");
}
}
public class RichBarChart : IChart
{
public string Title { get; set; }
public RichBarChart(string title)
{
Title = title;
}
public void GenerateChart()
{
Console.WriteLine($"Drawing a Rich Bar chart with title {Title}");
}
}
public class RichPieChart : IChart
{
public string Title { get; set; }
public RichPieChart(string title)
{
Title = title;
}
public void GenerateChart()
{
Console.WriteLine($"Drawing a Rich Pie chart with title {Title}");
}
}
public class ChartCreaterFree : IChartCreater
{
public IChart GetChart(string type, string title)
{
if (type=="bar")
{
return new BarChart(title);
}
if (type=="pie")
{
return new PieChart(title);
}
return null;
}
}
付费类型
public class ChartCreaterPaid : IChartCreater
{
public IChart GetChart(string type, string title)
{
if (type == "bar")
{
return new RichBarChart(title);
}
if (type == "pie")
{
return new RichPieChart(title);
}
return null;
}
}
class Program
{
static void Main(string[] args)
{
IChartCreater createrFree = new ChartCreaterFree();
IChartCreater createrPaid = new ChartCreaterPaid();
IChart bar = createrFree.GetChart("bar", "a free bar chart");
IChart pie = createrPaid.GetChart("pie", "a paid pie chart");
bar.GenerateChart();
pie.GenerateChart();
Console.ReadLine();
}
}
标签:stat void uml类图 getchar 柱状图 版本 hba 控制台 不同
原文地址:https://www.cnblogs.com/Saints/p/12596951.html