张德长

导航

设计模式之简单工厂SimpleFactory的实现

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

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

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

        public void Display()
        {
            Console.WriteLine("显示柱状图");
        }
    }
internal class SimpleFactory
    {
        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 class Program
    {
        static void Main(string[] args)
        {
            Chart chart;
            SimpleFactory factory = new SimpleFactory();
            chart = factory.GetChart("pie");
            chart.Display();
            Console.Read();
        }
    }

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