张德长

导航

设计模式之简单工厂SimpleFactory的实现(配置文件)

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
	<appSettings>
		<add key="chartType" value="histogram" />
	</appSettings>
</configuration>
 public Chart GetChart(string type)
        {
            Chart chart = null;
            switch (type)
            {
                case "histogram":
                    chart= new HistogramChart();
                    break;
                case "pie":
                    chart =new PieChart();
                    break;
                case "line":
                    chart = new LineChart();
                    break;
                default:
                    break;
            }
            return chart;

        }
    }
internal interface Chart
    {
         void Display();
    }
internal class HistogramChart:Chart
    {
        public HistogramChart() { Console.WriteLine("创建柱状图"); }

        public void Display()
        {
            Console.WriteLine("显示柱状图");
        }
    }
internal class PieChart : Chart
    {
        public PieChart() { Console.WriteLine("创建饼状图"); }

        public void Display()
        {
            Console.WriteLine("显示饼状图");
        }
    }
internal class LineChart : Chart
    {
        public LineChart() { Console.WriteLine("创建折线图"); }

        public void Display()
        {
            Console.WriteLine("显示折线图");
        }
    }
internal class Program
    { 
        static void Main(string[] args)
        {
            Chart chart;
            SimpleFactory factory = new SimpleFactory();
            string chartType = ConfigurationManager.AppSettings["chartType"];
            chart = factory.GetChart(chartType);
            chart.Display();
            Console.Read();
        }
    }

posted on 2022-04-02 12:55  张德长  阅读(56)  评论(0编辑  收藏  举报