Chapter 10. 设计模式--工厂模式

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

namespace ConsoleApplication9
{
    /*设计模式:工厂模式 */

    //父类:NoteBook
    public abstract class NoteBook
    {
        public abstract void SayHello();
    }
    
    //子类:
    public class ASUS : NoteBook
    {
        public override void SayHello()
        {
            Console.WriteLine("我是华硕笔记本");
        }
    }

    public class Acer : NoteBook
    {
        public override void SayHello()
        {
            Console.WriteLine("我是宏基笔记本");
        }
    }

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

    public class DELL : NoteBook
    {
        public override void SayHello()
        {
            Console.WriteLine("我是戴尔笔记本");
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("请输入您要的笔记本品牌:");
            string brand = Console.ReadLine();
            NoteBook nb = GetNoteBook(brand);
            nb.SayHello();

            Console.ReadLine();      
        }

        /// <summary>
        /// 简单工厂的核心(根据用户的输入,创建对象赋值给父类)
        /// </summary>
        /// <param name="brand">品牌</param>
        /// <returns></returns>
        public static NoteBook GetNoteBook(string brand)
        {
            NoteBook nb = null;
            switch(brand)
            {
                case "ASUS": nb =new ASUS();
                    break;
                case "IBM": nb = new IBM();
                    break;
                case "DELL": nb = new DELL();
                    break;
                case "Acer": nb = new Acer();
                    break;
            }
            return nb;
        }
    }
}

 

原文地址:https://www.cnblogs.com/xiao55/p/5761627.html