步步为营-08-设计模式-简单工厂

电脑品牌判断器
本文介绍了一个简单的电脑品牌判断器的设计与实现。通过定义抽象的电脑类及宏碁和戴尔两个子类,并使用工厂模式返回相应的实例。用户输入品牌名称后,程序将判断并输出对应的电脑品牌。

一以贯之 :把子类看作父类,统一看待

假设用户输入一个电脑品牌,判断该品牌是否存在

1 定义一个抽象"电脑类"

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

namespace ComputerBand
{
 public abstract class Computer
    {
      public abstract void SayHi();
    }
}
Computer

2 定义两个子类(宏碁和戴尔)

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

namespace ComputerBand
{
    class Arce:Computer
    {
        public override void SayHi()
        {
            Console.WriteLine("我是宏碁");
        }
    }
}
Arce
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ComputerBand
{
    class Dell:Computer

    {
        public override void SayHi()
        {
            Console.WriteLine("我是戴尔!");
        }
    }
}
Dell

3 关键来了,定义一个工厂类,返回值为父类

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

namespace ComputerBand
{
   public class Factory
    {
      public static Computer GetComputer(string brand)
       {
           Computer cp = null;
           switch (brand)
           {
               case "arce":
                   cp = new Arce();
                   break;
               case "Dell":
                    cp = new Dell();
                   break;               
               default:
                   break;
           }
           return cp;
       }
    }
}
Factory

4 看看如何调用

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

namespace ComputerBand
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("请输入要查询品牌!");
            string brand = Console.ReadLine();
            Computer cp = Factory.GetComputer(brand);
            if (cp != null)
            {
                cp.SayHi();
            }
            else {
                Console.WriteLine( "输入的电脑品牌不存啊!");
            }
            Console.Read();
        }
    }
}
main

运行效果

 

转载于:https://www.cnblogs.com/YK2012/p/6707839.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值