设计模式:简单工厂模式

2022-06-30  本文已影响0人  山猪打不过家猪

设计模式:设计项目的一种方式,帮助我们开发中的遇到的问题。


image.png
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;


namespace _fangwenxiushifu
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("请输入笔记本品牌");
            string brand_name = Console.ReadLine();
            NoteBook nb = GetNoteBook(brand_name);
            nb.SayHello();
            Console.ReadKey();
        }

        public abstract class NoteBook
        {
            public abstract void SayHello();
        }

        public class Lenovo : NoteBook
        {
            public override void SayHello()
            {
                Console.WriteLine("我是联想电脑");
            }
        }

        public class IBM : NoteBook
        {
            public override void SayHello()
            {
                Console.WriteLine("我是IBM");
            }
        }

        //简单工厂模式最核心,根据用户输入创建对象复制给父类
        public static NoteBook GetNoteBook(string brand_name)
        {
            NoteBook nb = null;
            switch (brand_name)
            {
                case "lenovo": nb = new Lenovo();
                    break;
                case "IBM": nb = new IBM();
                    break;

            }

            return nb;
        }

    }
}

练习:超市收银

image.png
上一篇 下一篇

猜你喜欢

热点阅读