简单工厂模式

当你需要什么,只需要传入一个正确的参数,就可以获取你所需要的对象,而无须知道其创建的细节。

接下来就用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();
        }
    }

结果如下:

 这里打印出来第一个实现里的内容。

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值