c# 实现简单工厂模式demo

微信交流Python、c#:15188607997

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

namespace _04简单工厂设计模式
{
    class Program
    {
        static void Main(string[] args)
        {
            // 生产电脑 ibm Lenovo Dell Acer
            // 模拟生产笔记本
            Console.WriteLine("输入笔记本型号:");
            string brand = Console.ReadLine();
            NoteBook nb = GetNoteBook(brand);
            nb.SayHello();
            Console.ReadKey();
        }
        // 返回值为父类类型
        public static NoteBook GetNoteBook(string brand)
        {
            NoteBook nb = null;
            switch (brand)
            {
                case "IBM": nb = new IBM();
                    break;
                case "Lenovo": nb = new Lenovo();
                    break;
                case "Acer":nb = new Acer();
                    break;
                case "Dell": nb = new Dell();
                    break; 
            }
            return nb;
        }
    }

    // 父类整为抽象类
    public abstract class NoteBook
    {
        // 此处需要对子类中要实现的方法进行抽象定义
        public abstract void SayHello();
    }

    public class IBM : NoteBook
    {
        // 子类中对父类中的抽象方法,进行重写
        public override void SayHello()
        {
            Console.WriteLine("我是IBM");
        }
    }

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

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

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

你可能感兴趣的:(c# 实现简单工厂模式demo)