简单工厂设计模式
1 class Program 2 { 3 static void Main(string[] args) 4 { 5 Console.WriteLine("请输入您想要的笔记本品牌"); 6 string brand = Console.ReadLine(); 7 NoteBook nb = GetNoteBook(brand); 8 nb.SayHello(); 9 Console.ReadKey(); 10 } 11 12 13 /// <summary> 14 /// 简单工厂的核心 根据用户的输入创建对象赋值给父类 15 /// </summary> 16 /// <param name="brand"></param> 17 /// <returns></returns> 18 public static NoteBook GetNoteBook(string brand) 19 { 20 NoteBook nb = null; 21 switch (brand) 22 { 23 case "Lenovo": nb = new Lenovo(); 24 break; 25 case "IBM": nb = new IBM(); 26 break; 27 case "Acer": nb = new Acer(); 28 break; 29 case "Dell": nb = new Dell(); 30 break; 31 } 32 return nb; 33 } 34 }
1 public abstract class NoteBook 2 { 3 public abstract void SayHello(); 4 }
1 public class Lenovo : NoteBook 2 { 3 public override void SayHello() 4 { 5 Console.WriteLine("我是联想笔记本,你联想也别想"); 6 } 7 }
1 public class Acer : NoteBook 2 { 3 public override void SayHello() 4 { 5 Console.WriteLine("我是鸿基笔记本"); 6 } 7 }
1 public class Dell : NoteBook 2 { 3 public override void SayHello() 4 { 5 Console.WriteLine("我是戴尔笔记本"); 6 } 7 }
1 public class IBM : NoteBook 2 { 3 public override void SayHello() 4 { 5 Console.WriteLine("我是IBM笔记本"); 6 } 7 }

浙公网安备 33010602011771号