简单工厂设计模式

来源:互联网 发布:php网站架构 编辑:程序博客网 时间:2024/06/05 17:46

今天第一次接触了“设计模式”这个概念,初步学习了简单工厂设计模式

 简单工厂最核心的部分 模拟工厂       
        用一个方法来模拟工厂生产笔记本的过程
        这个工厂最终要制造出(返回)一个笔记本的父类
        根据用户输入的品牌来创建笔记本对象
        返回一个父类,但父类中装的是子类对象
        之后再使用多态,可以屏蔽子类之间的差异性

 

一个笔记本工厂的例子

代码:

using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace _03简单工厂设计模式{    class Program    {        static void Main(string[] args)        {            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 "Lenovo":                    nb = new Lenove();                    break;                case "IBM":                    nb = new IBM();                    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 Lenove : NoteBook    {        public override void SayHello()        {            Console.WriteLine("我是联想笔记本");        }    }    public class Acer : NoteBook    {         public override void SayHello()        {            Console.WriteLine("我是宏基笔记本");        }    }    public class Dell : NoteBook    {        public override void SayHello()        {            Console.WriteLine("我是戴尔笔记本");        }    }    public class IBM : NoteBook    {        public override void SayHello()        {            Console.WriteLine("我是IBM笔记本");        }    }}


 

0 0
原创粉丝点击