自己CSDN blog 上回收来的,以后都集中到这里了。
还是以快餐店做例子,简单工厂模式相当于家庭作坊,随着社会的进步,分工变细,所有快餐不再是一个师父包办,而是出现了面点师,米饭师(呵呵,不知道有没有这个,反正大家明白就行),面包师分别负责专门的食物制作。这就是工厂模式,请看下面的例子:
using System; namespace FactoryPattern { /// <summary> /// 工厂模式示例 /// </summary> class FactoryPattern { public static Chef nChef,rChef,bChef; public static Food noodle,rice,bread; /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main(string[] args) { //调用示例 nChef=new NoodlChef(); nChef.MakeFood(); rChef=new RiceChef(); rChef.MakeFood(); bChef=new BreadChef(); bChef.MakeFood(); Console.ReadLine(); } } class BadFoodException: System.Exception { public BadFoodException(string strMsg) { Console.WriteLine(strMsg); } } //定义各种快餐 public interface Food { //烹饪 void Cook(); //卖出 void Sell(); } public class Noodle:Food { public Noodle() { Console.WriteLine("\nThe Noodle is made.."); } private int price; public void Cook() { Console.WriteLine("\nNoodle is cooking..."); } public void Sell() { Console.WriteLine("\nNoodle has been sold..."); } public int Price { get{return this.price;} set{price=value;} } } public class Rice:Food { public Rice() { Console.WriteLine("\nThe Rice is made .."); } private int price; public void Cook() { Console.WriteLine("\nRice is cooking..."); } public void Sell() { Console.WriteLine("\nRice has been sold..."); } public int Price { get{return this.price;} set{price=value;} } } public class Bread:Food { public Bread() { Console.WriteLine("\nThe Bread is made...."); } private int price; public void Cook() { Console.WriteLine("\nBread is cooking..."); } public void Sell() { Console.WriteLine("\nBread has been sold..."); } public int Price { get{return this.price;} set{price=value;} } } //定义厨师接口,并分别定义面条师,米饭师,面包师 public interface Chef { //做饭 Food MakeFood(); } //面条师负责制作面条 class NoodlChef:Chef { public Food MakeFood() { return new Noodle(); } } //米饭师负责米饭 class RiceChef:Chef { public Food MakeFood() { return new Rice(); } } //面包师负责做面包 class BreadChef:Chef { public Food MakeFood() { return new Bread(); } } }