简单工厂:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AdapterDemo { class Program { static void Main(string[] args) { //通过工厂创建一个产品的实例 // 客户想点一个西红柿炒蛋 Food food1 = FoodSimpleFactory.CreateFood("西红柿炒蛋"); food1.Print(); // 客户想点一个土豆肉丝 Food food2 = FoodSimpleFactory.CreateFood("土豆肉丝"); food2.Print(); Console.Read(); } } /// <summary> /// 菜抽象类 /// </summary> public interface Food { // 输出点了什么菜 string Print(); } /// <summary> /// 西红柿炒鸡蛋这道菜 /// </summary> public class TomatoScrambledEggs : Food { public string Print() { Console.WriteLine("一份西红柿炒蛋!"); return string.Empty; } } /// <summary> /// 土豆肉丝这道菜 /// </summary> public class ShreddedPorkWithPotatoes : Food { public string Print() { Console.WriteLine("一份土豆肉丝"); return string.Empty; } } /// <summary> /// 简单工厂类, 负责 炒菜 /// </summary> public class FoodSimpleFactory { public static Food CreateFood(string type) { Food food = null; if (type.Equals("土豆肉丝")) { food = new ShreddedPorkWithPotatoes(); } else if (type.Equals("西红柿炒蛋")) { food = new TomatoScrambledEggs(); } return food; } } }