C#设计模式(2)——简单工厂模式(Factory )

我们通过 Factory 创建对象不同的对象。

例如:如果创建一个汽车的接口,通过 工厂Factory 创建实现接口的对象,根据我们的选择来创建不同的对象。

创建汽车接口

    /// <summary>
    /// 简单工厂模式
    /// </summary>
    public interface IAutoCarMake
    {
        /// <summary>
        /// 创建汽车
        /// </summary>
        void CreateAutoCar();
    }

创建两个派生类,分别实现创建不同颜色的两种汽车

    /// <summary>
    /// 红色小轿车
    /// </summary>
    public class _RedCar: IAutoCarMake
    {
        public void CreateAutoCar()
        {
            Console.WriteLine("生成红色小轿车");
        }
    }
    /// <summary>
    /// 蓝色小轿车
    /// </summary>
    public class _BlueCar : IAutoCarMake
    {
        public void CreateAutoCar()
        {
            Console.WriteLine("生成蓝色小轿车");
        }
    }

通过工厂类生成不同的对象实例

    /// <summary>
    /// 简单工厂模式-工厂类
    /// </summary>
    public class Factory
    {
        public IAutoCarMake CreateAutoCar(string flag)
        {
            switch (flag)
            {
                case "red":
                    return new _RedCar();
                case "blue":
                    return new _BlueCar();
            }
            return null;
        }

        static void Main(string[] args)
        {
            IAutoCarMake parents = new Factory().CreateAutoCar("red");

            IAutoCarMake parents = new Factory().CreateAutoCar("blue");

            parents.CreateAutoCar();

            Console.ReadKey();
        }
    }

 

 

posted on 2018-02-26 20:48  夜、微凉 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/wwj1992/p/8475971.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值