3.工厂方法模式(Factory Method)

using System;
using System.Reflection;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //需要什么食物,创建什么工厂
            FactoryCreate _factorycreate = new YaJiaFactoryCreate();
            Food _food = _factorycreate.Create();
            _food.MakeFood();

            //反射机制 选择实例化的类型
            FactoryCreate _factorycreate2;
            _factorycreate2 = (FactoryCreate)Assembly.Load("ConsoleApplication1").CreateInstance("ConsoleApplication1." + "YaBoFactoryCreate");
            Food _food2 = _factorycreate2.Create();
            _food2.MakeFood();
        }
    }

    /// <summary>
    /// 食物接口或抽象类
    /// </summary>
    public abstract class Food
    {
        /// <summary>
        /// 生产食物
        /// </summary>
        public abstract void MakeFood();
    }

    /// <summary>
    /// 工厂接口或抽象类
    /// </summary>
    public abstract class FactoryCreate
    {
        public abstract Food Create();
    }

    /// <summary>
    /// 鸭脖工厂
    /// </summary>
    public class YaBoFactoryCreate : FactoryCreate
    {
        public override Food Create()
        {
            return new YaBo();
        }
    }

    /// <summary>
    /// 鸭架工厂
    /// </summary>
    public class YaJiaFactoryCreate : FactoryCreate
    {
        public override Food Create()
        {
            return new YaJia();
        }
    }

    /// <summary>
    /// 生产鸭脖
    /// </summary>
    public class YaBo : Food
    {
        public override void MakeFood()
        {
            Console.WriteLine("鸭脖");
            Console.ReadLine();
        }
    }

    /// <summary>
    /// 生产鸭架
    /// </summary>
    public class YaJia : Food
    {
        public override void MakeFood()
        {
            Console.WriteLine("鸭架");
            Console.ReadLine();
        }
    }
}

 

转载于:https://www.cnblogs.com/lgxlsm/p/4629008.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值
>