zoukankan      html  css  js  c++  java
  • 步步为营-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

    运行效果

  • 相关阅读:
    [CSAPP笔记][第一章计算机系统漫游]
    [暂停学习几天]
    [汇编学习笔记][第十七章使用BIOS进行键盘输入和磁盘读写
    [汇编学习笔记][第十六章直接定址表]
    [汇编语言学习笔记][第十五章 外中断]
    [汇编学习笔记][第十四章 端口]
    [汇编学习笔记][第十三章int指令]
    [汇编学习笔记][第十二章内中断]
    [汇编学习笔记][第十一章标志寄存器]
    [汇编学习笔记][第十章 CALL和RET指令]
  • 原文地址:https://www.cnblogs.com/YK2012/p/6707839.html
Copyright © 2011-2022 走看看