1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace _03簡單工廠設計模式 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 Console.WriteLine("請輸入您想要的筆記本品牌"); 14 string brand = Console.ReadLine(); 15 NoteBook nb = GetNoteBook(brand); 16 nb.SayHello(); 17 Console.ReadKey(); 18 } 19 20 21 /// <summary> 22 /// 簡單工廠的核心 根據使用者的輸入建立物件賦值給父類 23 /// </summary> 24 /// <param name="brand"></param> 25 /// <returns></returns> 26 public static NoteBook GetNoteBook(string brand) 27 { 28 NoteBook nb = null; 29 switch (brand) 30 { 31 case "Lenovo": nb = new Lenovo(); 32 break; 33 case "IBM": nb = new IBM(); 34 break; 35 case "Acer": nb = new Acer(); 36 break; 37 case "Dell": nb = new Dell(); 38 break; 39 } 40 return nb; 41 } 42 } 43 44 public abstract class NoteBook 45 { 46 public abstract void SayHello(); 47 } 48 49 public class Lenovo : NoteBook 50 { 51 public override void SayHello() 52 { 53 Console.WriteLine("我是聯想筆記本,你聯想也別想"); 54 } 55 } 56 57 58 public class Acer : NoteBook 59 { 60 public override void SayHello() 61 { 62 Console.WriteLine("我是鴻基筆記本"); 63 } 64 } 65 66 public class Dell : NoteBook 67 { 68 public override void SayHello() 69 { 70 Console.WriteLine("我是戴爾筆記本"); 71 } 72 } 73 74 public class IBM : NoteBook 75 { 76 public override void SayHello() 77 { 78 Console.WriteLine("我是IBM筆記本"); 79 } 80 } 81 }