继承之简单工厂

简单工厂实现的流程:

1.创建抽象产品类
2.创建具体产品的
3.创建工厂类
4.客户端调用工厂类
5.使用

下面是一个简单的示例代码,实现的功能:

提示用户输入喜欢的水果名称,调用显示该类水果的吃法

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 代码操练_简单工厂
{
    //1.创建抽象产品类    
    class Fruit
    { 
    
    }
    //2.创建具体产品类(苹果)
    class Apple : Fruit
    {
        public void EatApple()
        {
            Console.WriteLine("我是苹果的吃法");

        }
    
    }
    //创建具体产品类(香蕉)
    class Banana : Fruit
    {
        public void EatBanana()
        {
            Console.WriteLine("我是香蕉的吃法");

        }

    }
    //创建具体产品类(梨)
    class Pear : Fruit
    {
        public void EatPear()
        {
            Console.WriteLine("我是梨的吃法");

        }

    }



    class Program
    {
        static void Main(string[] args)
        {

            Console.WriteLine("你喜欢吃什么水果:1.苹果2.香蕉3.梨");
            //接受用户输入的类别
            string result = Console.ReadLine();

            //抽象类为空
            Fruit fr = null;

            //3.创建工厂类
            switch (result)
            { 
                case "苹果":
                    fr=new Apple();
                    break;
            }

             switch (result)
            { 
                 case "香蕉":
                    fr=new Banana();
                    break;
            }

             switch (result)
            { 
                 case "梨":
                    fr=new Pear();
                    break;
            }

            //客户端调用工厂类
             if (fr is Apple)
             {

                 ((Apple)fr).EatApple();
             }

             if (fr is Banana)
            {

                ((Banana)fr).EatBanana();
            }

            if (fr is Pear)
            {

                ((Pear)fr).EatPear();
            }

            //Console.WriteLine(result);
            Console.ReadKey();
            
            

        }
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值