C# - 简单工厂模式

代码:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace 简单工厂模式
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             Console.Write("请输入你要的电脑:");
14             string brand = Console.ReadLine();
15             Notepad nt = GC(brand);
16             nt.SayHello();
17             Console.ReadKey();
18         }
19 
20 
21         /// <summary>
22         /// 简单工厂模式
23         /// </summary>
24         /// <param name="brand"></param>
25         /// <returns></returns>
26         public static Notepad GC(string brand)
27         {
28             Notepad nt = null;
29 
30             switch (brand)
31             {
32                 //核心代码
33                 case "Lenovo": nt = new Lenovo(); break;
34                 case "Acer": nt = new Acer(); break;
35                 case "IBM": nt = new IBM(); break;
36                 default:break;
37             }
38 
39             return nt;
40         }
41     }
42 
43     /// <summary>
44     /// 父类
45     /// </summary>
46     public abstract class Notepad
47     {
48         public abstract void SayHello();
49     }
50 
51     /// <summary>
52     /// 宏基
53     /// </summary>
54     public class Acer : Notepad
55     {
56         public override void SayHello()
57         {
58             Console.WriteLine("我是宏基!");
59         }
60     }
61 
62     /// <summary>
63     /// 联想
64     /// </summary>
65     public class Lenovo : Notepad
66     {
67         public override void SayHello()
68         {
69             Console.WriteLine("我是联想!");
70         }
71     }
72 
73     /// <summary>
74     /// IBM
75     /// </summary>
76     public class IBM : Notepad 
77     {
78         public override void SayHello()
79         {
80             Console.WriteLine("我是IBM!");
81         }
82     }
83 }

 

posted on 2015-05-28 12:26  ultrastrong  阅读(164)  评论(0编辑  收藏  举报