private void DoFinalOutput() { lock (_isDone) { if (_isDone.All(temp => temp)) { // 所有都完成 AbstractFood maxScoreFood = null; int maxScore = -1; for (int i = 0; i < _maxScores.Length; i++) { var score = _maxScores[i]; if (score > maxScore) { maxScore = score; maxScoreFood = _maxScoreFoods[i]; } } Console.WriteLine(); var foregroundColor = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine("最高分的菜是:" + maxScoreFood.GetType().Name + "," + maxScore); Console.ForegroundColor = foregroundColor; button1.Enabled = true; } } }
private OrderMenu() { //加载配置文件 XMLTool xmlTool = new XMLTool("CfgFiles\\foodMenu.xml"); XElement xRoot = xmlTool.LoadXml(); var foodList = xRoot.Elements("Food"); Type type = typeof(AbstractFood); foreach (var item in foodList) { //1:找到类的名称 var csName = item.Element("FoodName").Value; //2:通过反射来实例化对象 Assembly assembly = Assembly.Load("NineFive.Model"); AbstractFood food = assembly.CreateInstance($"NineFive.Model.OrderSystem.{csName}Food") as AbstractFood; if (food == null) { continue; } //3:赋值 foreach (var propItem in type.GetProperties()) { var propValue = item.Element(propItem.Name)?.Value; if (!string.IsNullOrEmpty(propValue)) { propItem.SetValue(food, Convert.ChangeType(propValue, propItem.PropertyType), null); } } AllFoods.Add(food); } }
virtual public bool setItem(GameObject item, GameObject player) { if (content == null) { lastPlayerInteracting = player; contentParent = item; content = item.GetComponent <AbstractFood>(); if (content != null && canProcess(content)) { state = State.CLOSED; loadBar.gameObject.SetActive(true); Rigidbody rb = contentParent.GetComponent <Rigidbody> (); rb.rotation = GetComponent <Rigidbody> ().rotation; rb.Sleep(); contentParent.transform.position = itemPos.position; updateFurniture(); process(true); return(true); } else { content = null; contentParent = null; } } return(false); }
// create by receiving string dll information, then create by reflection public static AbstractFood CreateInstanceByReflectionInfo(string typeDll) { Assembly assembly = Assembly.Load(typeDll.Split(',')[1]); Type type = assembly.GetType(typeDll.Split(',')[0]); AbstractFood result = (AbstractFood)Activator.CreateInstance(type); return(result); }
public override bool Equals(AbstractFood other) { if (this._name.Equals(other.Name) && other.GetType() == this.GetType()) { return true; } else { return false; } }
protected override bool canProcess(AbstractFood food) { if (content.getSlicePerm()) { return(true); } else { return(false); } }
public static void PrintMostHighFood(List <Consumer> consumerList) { List <AbstractFood> listAbstractFood = new List <AbstractFood>(); foreach (var consumer in consumerList) { AbstractFood abstractFood = consumer.ConsumerContext.AbstractFoodList.OrderByDescending(z => z.DishContext.Review).ToList()[0]; listAbstractFood.Add(abstractFood); } listAbstractFood.OrderByDescending(y => y.DishContext.Review).ToList(); PrintHelper.PrintWrite($"客人评分最高的菜是{listAbstractFood[0].Name}", ConsoleColor.Red); }
public static void ConsumerIsComing(Consumer consumer) { ConsumerContext consumerContext = new ConsumerContext { ConsumerName = consumer.Name }; consumer.Show(consumerContext); for (int i = 0; i < 5; i++) { AbstractFood abstractFood = CreateFood(consumer); consumerContext.AbstractFoodList.Add(abstractFood); } PrintResult(consumer); }
virtual public GameObject getItem() { if (content != null) { process(false); state = State.OPEN; loadBar.gameObject.SetActive(false); contentParent.GetComponent <Rigidbody> ().WakeUp(); content = null; updateFurniture(); return(contentParent); } else { return(null); } }
private static AbstractFood CreateFood(Consumer consumer) { Console.WriteLine(); AbstractFood abstractFood = SimpleDishFactory.PointDish(new RandomHelper().GetNumber(1, 10)); abstractFood.PointDish(new DishContext { Id = abstractFood.Id, ConsumerName = consumer.Name, Quantity = 1, TableNumber = "002", HotType = "正常", PrintColor = consumer.PrintColor }); abstractFood = new AbstractCutFoodDecorator(abstractFood); abstractFood = new AbstractWashFoodDecorator(abstractFood); abstractFood = new AbstractBuyFoodDecorator(abstractFood); abstractFood = new AbstractPendFoodDecorator(abstractFood); abstractFood = new AbstractServingFoodDecorator(abstractFood); abstractFood.DoDish(); abstractFood.Taste(); abstractFood.Review(); return(abstractFood); }
override protected bool canProcess(AbstractFood food) { return(true); }
public FoodDecoratorCut(AbstractFood food) : base(food) { Console.WriteLine("Food Decorator Cut constructor"); }
static void Main(string[] args) { try { #region 1.0 普通的展示菜的方法 { Console.WriteLine($"{prefix}普通方法{prefix}"); NineFive.Model.Food.BeefFood beefFood = new NineFive.Model.Food.BeefFood(); beefFood.Show(); NineFive.Model.Food.FishFood fishFood = new NineFive.Model.Food.FishFood(); fishFood.Show(); NineFive.Model.Food.ChopFood chopFood = new NineFive.Model.Food.ChopFood(); chopFood.Show(); } #endregion #region 2.0 简单工厂点菜 { //简单工厂:如果要加一类修改case 条件,添加类别 //长处: 简单,有效,类型创建剥离出来了 //短处:添加或者删除类,需要变更DLL,还需要该case或者if 条件 Console.WriteLine($"{prefix}简单工厂{prefix}"); BaseFood beefFood = SimpleFoodFactory.Create(FoodType.Beef); beefFood.Show(); BaseFood fishFood = SimpleFoodFactory.Create(FoodType.Fish); fishFood.Show(); BaseFood chopFood = SimpleFoodFactory.Create(FoodType.Chop); chopFood.Show(); } #endregion #region 3.0 工厂方法 { Console.WriteLine($"{prefix}工厂方法{prefix}"); //工厂方法:如果要加一类,只需添加工厂就可以 //长处: 创建单一产品的时候只需结合反射和配置文件可以完美的实现对象的创建 //短处:增加和修改产品依然需要变更DLL文件 IFoodFactory beefFactory = new BeefFactory(); beefFactory.Create().Show(); IFoodFactory fishFactory = new FishFactory(); fishFactory.Create().Show(); IFoodFactory chopFactory = new ChopFactory(); chopFactory.Create().Show(); } #endregion #region 4.0 抽象工厂 { Console.WriteLine($"{prefix}抽象工厂{prefix}"); //抽象工厂:如果要加一类,只需添加工厂实现父类就可 //长处: 在创建多产品的时候非常适用 //短处:因为父类中有多产品,和父类耦合度过高 AbsFoodFactory sFactory = new SouthFoodFactory(); sFactory.CreateRice().Show(); sFactory.CreateSoup().Show(); sFactory.CreateBeef().Show(); sFactory.CreateFish().Show(); sFactory.CreateChop().Show(); AbsFoodFactory nFactory = new NorthFoodFactory(); nFactory.CreateRice().Show(); nFactory.CreateSoup().Show(); nFactory.CreateBeef().Show(); nFactory.CreateFish().Show(); nFactory.CreateChop().Show(); } #endregion #region 5.0 点菜系统 { bool isExist = true; OrderMenu.GetInstance(); while (isExist) { //1:显示菜单 OrderMenu.GetInstance().ShowMenu(); //2:等待用户输入要点的菜 string foods = Console.ReadLine(); if (foods.Trim().Length == 0) { //new OrderSystem.OrderMenu().ShowMenu(); continue; } //3:显示我点的菜名称 string[] strList = foods.Split(','); if (strList.Contains("0")) { isExist = false; continue; } List <int> foodIds = new List <int>(); foreach (var item in strList) { foodIds.Add(Convert.ToInt32(item)); } OrderMenu.GetInstance().AllFoods.Where(u => foodIds.Contains(u.Id)).OrderBy(u => u.Id).ToList().ForEach(u => { Console.WriteLine($"我点的菜是:{u.FoodName},描述:{u.Describe}"); }); } } #endregion #region 6.0 顾客点菜 { OrderMenu orderMenu = OrderMenu.GetInstance(); //1:创建客人 List <Customer> customers = new List <Customer>(); Customer aCustomer = new Customer("甲"); Customer bCustomer = new Customer("乙"); Customer cCustomer = new Customer("丙"); customers.Add(aCustomer); customers.Add(bCustomer); customers.Add(cCustomer); //2:客人开始点菜 Console.WriteLine($"{prefix}三个客人开始点菜了{prefix}"); //2.1 加载程序集,通过反射来加载菜的程序集 Assembly assembly = Assembly.Load("NineFive.Model"); //3:创建多线程 TaskFactory taskFactory = new TaskFactory(); List <Task> tasks = new List <Task>(); tasks.Add(taskFactory.StartNew(() => { //1:随机点3个菜 List <AbstractFood> foods = GetFoods(); foods.ForEach(u => { //通过反射来创建菜的对象 AbstractFood newFood = u.Clone() as AbstractFood; aCustomer.Foods.Add(newFood); }); //2:开始品菜 aCustomer.Foods.ForEach(u => { //装饰器模式实现 AbstractFood food = new BaseFoodDecorate(u); food = new BeforeCookDecorate(food); food = new AfterCookDecorate(food); //做菜 food.Cook(); //品尝 food.Taste(); //点评 food.Comment(); }); })); tasks.Add(taskFactory.StartNew(() => { //1:随机点3个菜 List <AbstractFood> foods = GetFoods(); foods.ForEach(u => { //通过反射来创建菜的对象 AbstractFood newFood = u.Clone() as AbstractFood; bCustomer.Foods.Add(newFood); }); //2:开始品菜 bCustomer.Foods.ForEach(u => { //做菜 u.Cook(); //品尝 u.Taste(); //点评 u.Comment(); }); })); tasks.Add(taskFactory.StartNew(() => { //1:随机点3个菜 List <AbstractFood> foods = GetFoods(); foods.ForEach(u => { //通过反射来创建菜的对象 AbstractFood newFood = u.Clone() as AbstractFood; cCustomer.Foods.Add(newFood); }); //2:开始品菜 cCustomer.Foods.ForEach(u => { //做菜 u.Cook(); //品尝 u.Taste(); //点评 u.Comment(); }); })); //4:三个客人都吃完了后,开始进行点评了 taskFactory.ContinueWhenAll(tasks.ToArray(), (ts) => { Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine("开始显示评选得分最高的菜"); customers.ForEach(u => { u.Foods.OrderByDescending(iu => iu.Score).ToList().ForEach(h => { Console.WriteLine($"{u.Name}:菜名:{h.FoodName},描述:{h.Describe},得分:{h.Score}"); }); }); }); } #endregion } catch (Exception ex) { Console.WriteLine($"异常信息:{ex.Message}"); } Console.ReadLine(); }
static void Main(string[] args) { #region normal pattern of program { //Console.WriteLine("*********************1 normal pattern of program****************"); //AbstractFood braisedPolkBall = new BraisedPolkBall(); //braisedPolkBall.ShowBasicInfo(); //braisedPolkBall.ShowCookMethod(); //braisedPolkBall.Taste(); //AbstractFood crabPackage = new CrabPackage(); //crabPackage.ShowBasicInfo(); //crabPackage.ShowCookMethod(); //crabPackage.Taste(); //AbstractFood squirrelFish = new SquirrelFish(); //squirrelFish.ShowBasicInfo(); //squirrelFish.ShowCookMethod(); //squirrelFish.Taste(); //Console.WriteLine("********************* End Of normal Pattern*******************************"); } #endregion #region simple factory { //Console.WriteLine("*********************2 simple factory, create instance with Enum****************"); //Console.WriteLine("******simple factory: create instance based on Enum, call different new Class() "); //AbstractFood braisedPolkBall = FoodSimpleFactory.CreateInstanceByNormal(FoodTypeEnum.BraisedPolkBall); //braisedPolkBall.ShowBasicInfo(); //braisedPolkBall.ShowCookMethod(); //braisedPolkBall.Taste(); //Console.WriteLine("************create instance from Config, then to Enum, then use simple factory "); //AbstractFood crabPackage = FoodSimpleFactory.CreateInstanceByConfig(); //crabPackage.ShowBasicInfo(); //crabPackage.ShowBasicInfo(); //crabPackage.Taste(); //Console.WriteLine("************create instance from Config, then use reflection to create class "); //AbstractFood squirrelFish = FoodSimpleFactory.CreateInstanceByReflection(); //squirrelFish.ShowBasicInfo(); //squirrelFish.ShowCookMethod(); //squirrelFish.Taste(); //Console.WriteLine("********************* End Of simple factory*******************************"); } #endregion #region Factory Method { //Console.WriteLine("**********************3 Factory Method*************************************"); //BaseFactory braisedPolkBallFactory = new BraisedPolkBallFactory(); //AbstractFood braisedPolkBall = braisedPolkBallFactory.CreateInstance(); //braisedPolkBall.ShowBasicInfo(); //braisedPolkBall.ShowCookMethod(); //braisedPolkBall.Taste(); //Console.WriteLine("**********************End of Factory Method*************************************"); } #endregion #region Abstract Factory { //Console.WriteLine("**********************4 Abstract Factory*************************************"); //IHuaiYangFoodAbstractFactory factory = new HuaiYangFoodAbstractFactory(); //Console.WriteLine("1 first dish"); //AbstractFood food = factory.CreateBraisedPolkBall(); //food.ShowBasicInfo(); //food.ShowCookMethod(); //food.Taste(); //Console.WriteLine("2 a soup"); //AbstractSoup soup = factory.CreateTomatoEggSoup(); //soup.ShowBasicInfo(); //soup.Taste(); //Console.WriteLine("**********************End of Abstract Factory*************************************"); } #endregion #region Console Menu { //Console.WriteLine("**********************5 Console Menu*************************************"); //Console.WriteLine("*****************************************************"); //FoodMenu menu = FoodMenu.CreateInstance(); //if (menu.FoodList != null && menu.FoodList.Count > 0) //{ // foreach (FoodModel model in menu.FoodList) // { // Console.WriteLine(string.Format("ID: {0}{1} Price: {2} Score: {3} ", // model.FoodId, // model.FoodName, // string.Format("{0:C}",model.Price), // model.FoodScore // ) ); // Console.WriteLine("*****************************************************"); // } //} //Console.WriteLine("please type in food id and press enter to continue..."); //while (true) //{ // if (!int.TryParse(Console.ReadLine(), out int input)) // { // LogHelper.WriteInfoLog("your input is not int, please try again", ConsoleColor.Red); // } // else // { // var selectedFood = menu.FoodList.FirstOrDefault(c => c.FoodId == input); // if (selectedFood == null) // { // LogHelper.WriteInfoLog("Sorry, we don't have that!",ConsoleColor.Red); // } // else // { // string msg = string.Format("You select dish: {0}, price: {1}, Score: {2}, price: {3}", // selectedFood.FoodId, // selectedFood.FoodName, // selectedFood.FoodScore, // string.Format("{0:C}",selectedFood.Price ) // ); // LogHelper.WriteInfoLog(msg, ConsoleColor.DarkGreen); // AbstractFood absFood = FoodSimpleFactory.CreateInstanceByReflectionInfo(selectedFood.SimpleFactory); // absFood.ShowBasicInfo(); // absFood.ShowCookMethod(); // break; // } // } //} //Console.WriteLine("**********************End of Console Menu*************************************"); } #endregion #region Single-thread order /* * { * Console.WriteLine("******************Single-thead order***************************"); * char[] tips = "Please see below".ToCharArray(); * for (int i = 0; i < tips.Length; i++) * { * Console.Write(tips[i]); * Thread.Sleep(100); * } * * Console.WriteLine(); * * FoodMenu menu = FoodMenu.CreateInstance(); * * OrderInfoList orderInfoList = OrderInfoList.CreateInstance(); * OrderModel order = orderInfoList._orderModel; * string msg1 = string.Format("{0} come to order. ", string.Join(", ", order.CustomerList)); * LogHelper.WriteInfoLog(msg1, ConsoleColor.DarkRed); * * * //List<Task> taskList = new List<Task>(); * Dictionary<string, Dictionary<AbstractFood, int>> dictionaryAll = * new Dictionary<string, Dictionary<AbstractFood, int>>(); * * List<Dictionary<AbstractFood, int>> allCustomerScoreDicList = new List<Dictionary<AbstractFood, int>>(); * foreach (var item in order.CustomerList) * { * allCustomerScoreDicList.Add(new Dictionary<AbstractFood, int>()); * } * * int k = 0; * foreach (string customer in order.CustomerList) * { * Dictionary<AbstractFood, int> oneCustomerScoreDic = allCustomerScoreDicList[k++]; * * * //taskList.Add( * // Task.Run( * // () => * { * List<FoodModel> orderList = menu.GetFoodListByRandom(); * string orderMsg = string.Format("Customer: {0} order these: {1}", customer, * string.Join(",", orderList.Select(c => c.FoodName))); * LogHelper.WriteInfoLog(orderMsg, ConsoleColor.DarkRed); * * foreach (FoodModel food in orderList) * { * AbstractFood foodChosen = * FoodSimpleFactory.CreateInstanceByReflectionInfo(food.SimpleFactory); * foodChosen.BaseFood.CustomerName = customer; * foodChosen.Cook(); * foodChosen.Taste(); * int score = foodChosen.Score(); * oneCustomerScoreDic.Add(foodChosen, score); * } * * int maxScore = oneCustomerScoreDic.Values.Max(); * foreach (var item in oneCustomerScoreDic.Where(d => d.Value == maxScore)) * { * Console.BackgroundColor = ConsoleColor.DarkRed; * Console.WriteLine( * $"@@@@@@{customer} 's favourite food is {item.Key.BaseFood.FoodName}" + * $", score is {item.Value} @@@@@@"); * Console.BackgroundColor = ConsoleColor.Black; * } * * * * } * // ) * // ); * } * * //Task.WaitAll(taskList.ToArray()); * Console.WriteLine("*****************All Customers' favourite*********************************"); * int maxAll = allCustomerScoreDicList.Max(d => d.Values.Max()); * for (int i = 0; i < order.CustomerList.Count; i++) * { * var dic = allCustomerScoreDicList[i]; * foreach (var item in dic.Where(d => d.Value == maxAll)) * { * Console.WriteLine($"{order.CustomerList[i]} " + * $"s favourite food is {item.Key.BaseFood.FoodName}" + * $", score is {item.Value}"); * } * } * } #endregion * * * #region multi-thread order * { * Console.WriteLine("******************Multi-thead order***************************"); * char[] tips = "Please see below".ToCharArray(); * for (int i = 0; i < tips.Length; i++) * { * Console.Write(tips[i]); * Thread.Sleep(100); * } * * Console.WriteLine(); * * FoodMenu menu = FoodMenu.CreateInstance(); * * OrderInfoList orderInfoList = OrderInfoList.CreateInstance(); * OrderModel order = orderInfoList._orderModel; * string msg1 = string.Format("{0} come to order. ", string.Join(", ", order.CustomerList)); * LogHelper.WriteInfoLog(msg1, ConsoleColor.DarkRed); * * * List<Task> taskList = new List<Task>(); * Dictionary<string, Dictionary<AbstractFood, int>> dictionaryAll = * new Dictionary<string, Dictionary<AbstractFood, int>>(); * * List<Dictionary<AbstractFood, int>> allCustomerScoreDicList = new List<Dictionary<AbstractFood, int>>(); * //must have a container containing multiple containers for each customer. * //if use multi-thread, sharing one container will cause issue, lock will affect efficiency. * //so must use separate container for each thread. * foreach (var item in order.CustomerList) * { * allCustomerScoreDicList.Add(new Dictionary<AbstractFood, int>()); * } * * int k = 0; * foreach (string customer in order.CustomerList) * { * Dictionary<AbstractFood, int> oneCustomerScoreDic = allCustomerScoreDicList[k++]; * * * taskList.Add( * Task.Run( * () => * { * List<FoodModel> orderList = menu.GetFoodListByRandom(); * string orderMsg = string.Format("Customer: {0} order these: {1}", customer, * string.Join(",", orderList.Select(c => c.FoodName))); * LogHelper.WriteInfoLog(orderMsg, ConsoleColor.DarkRed); * * foreach (FoodModel food in orderList) * { * AbstractFood foodChosen = * FoodSimpleFactory.CreateInstanceByReflectionInfo(food.SimpleFactory); * foodChosen.BaseFood.CustomerName = customer; * foodChosen.Cook(); * foodChosen.Taste(); * int score = foodChosen.Score(); * oneCustomerScoreDic.Add(foodChosen, score); * } * * int maxScore = oneCustomerScoreDic.Values.Max(); * foreach (var item in oneCustomerScoreDic.Where(d => d.Value == maxScore)) * { * Console.BackgroundColor = ConsoleColor.DarkRed; * Console.WriteLine( * $"@@@@@@{customer} 's favourite food is {item.Key.BaseFood.FoodName}" + * $", score is {item.Value} @@@@@@"); * Console.BackgroundColor = ConsoleColor.Black; * } * } * ) * ); * } * * Task.WaitAll(taskList.ToArray()); // wait for every task finish eating. * Console.WriteLine("*****************All Customers' favourite*********************************"); * int maxAll = allCustomerScoreDicList.Max(d => d.Values.Max()); * for (int i = 0; i < order.CustomerList.Count; i++) * { * var dic = allCustomerScoreDicList[i]; * foreach (var item in dic.Where(d => d.Value == maxAll)) * { * Console.WriteLine($"{order.CustomerList[i]} " + * $"s favourite food is {item.Key.BaseFood.FoodName}" + * $", score is {item.Value}"); * } * } * } */ #endregion #region decorator { Console.WriteLine("**********************Decorator************************************"); AbstractFood food = FoodSimpleFactory.CreateInstanceByNormal(FoodTypeEnum.BraisedPolkBall); //do before base.Cook(); food = new FoodDecoratorCut(food); food = new FoodDecoratorClean(food); //do after base.Cook(); food = new FoodDecoratorPlace(food); food = new FoodDecoratorShow(food); //do before base.Cook(); //even put at the end, execute before base.Cook() food = new FoodDecoratorBuy(food); food.Cook(); } #endregion #region observer /* * { * AbstractFood food = FoodSimpleFactory.CreateInstanceByNormal(FoodTypeEnum.BraisedPolkBall); * food.PerfactScoreHandle += () => * { * Console.WriteLine("Customer buy...."); * }; * * food.PerfactScoreHandle += () => { Console.WriteLine("Journalist1 report....."); }; * * food.PerfactScoreHandle += () => { Console.WriteLine("Journalist2 report......"); }; * * food.Score(5); * * } * */ #endregion Console.ReadKey(); }
static void Main(string[] args) { { #region 1 每个人要学会做几个菜,不低于3个。。。先不用任何工厂方法,普通实现,分别展示几个菜,好不好吃 Console.WriteLine("1 每个人要学会做几个菜,不低于3个。。。先不用任何工厂方法,普通实现,分别展示几个菜,好不好吃"); ChiliFryMeat chiliFryMeat = new ChiliFryMeat(); chiliFryMeat.Show(); TasteSnake tasteSnake = new TasteSnake(); tasteSnake.Show(); WoundBloodWang woundBloodWang = new WoundBloodWang(); woundBloodWang.Show(); #endregion } { #region 2 用简单工厂实现客人点菜,而不是让客人自己做菜(文字说明:如果要加一个菜,需要修改什么,考虑下简单工厂的长处和短处) Console.WriteLine(); Console.WriteLine("2 用简单工厂实现客人点菜,而不是让客人自己做菜"); Consumer consumer = new Consumer { Name = "张山" }; AbstractFood baseDish = SimpleDishFactory.PointDish(1); DishContext pointDishContext = new DishContext() { ConsumerName = consumer.Name, TableNumber = "001", Quantity = 1, HotType = "特辣" }; baseDish.PointDish(pointDishContext); #endregion //简单工厂长处:上层不再负责创建细节,把细节交给工厂,上层调用简单 //简单工厂短处:1.工厂内部复杂性增加,耦合. // 2.新增菜品,如果不通过反射则必须修改原来的工厂类,破坏封装 } { #region 3 用工厂方法实现客人点菜,而不是让客人自己做菜 Console.WriteLine(); Console.WriteLine("3 用工厂方法实现客人点菜,而不是让客人自己做菜"); Consumer consumer = new Consumer { Name = "李四" }; IFactory factory = DishFactoryMethod.CreateFactory(105); AbstractFood baseDish = factory.CreateDish(); DishContext pointDishContext = new DishContext() { ConsumerName = consumer.Name, TableNumber = "002", Quantity = 2, HotType = "中辣" }; baseDish.PointDish(pointDishContext); #endregion //工厂方法长处:1.工厂内部不再封装全部细节,解决了简单工厂的耦合问题 。 // 2.创建新的菜品,不再需要修改原来的工厂。对修改封闭 //工厂方法短处:1.代码麻烦,一个类一个工厂. // 2.新增菜品,必须新增一个类和他对应的工厂 } #region 4 用抽象工厂,每个工厂都能做三个菜、一个汤、一个主食 Console.WriteLine(); Console.WriteLine("4 用抽象工厂,每个工厂都能做三个菜、一个汤、一个主食"); { Consumer consumer = new Consumer { Name = "湖南牙子" }; Console.WriteLine("来了一个湖南牙子,点了一个湘菜套餐。如下:"); DishAbstractFactory dishAbstractFactory = new HuNanDishFactory(); dishAbstractFactory.Show(); } { Consumer consumer = new Consumer { Name = "东北大汉" }; Console.WriteLine("来了一个东北大汉,点了一桌东北菜。如下:"); DishAbstractFactory dishAbstractFactory = new NorthEastDishFactory(); dishAbstractFactory.Show(); } #endregion //抽象工厂长处:1.不再一个类对应一个工厂,而是按规则对应一组类,解决了工厂方法工厂过多的问题。。 // 2.创建新的菜品,不再需要修改原来的工厂。对修改封闭 //抽象工厂短处:1.当规则改变时,则修改较麻烦 // 2.并不是全部的对修改封闭 #region 5 做个点菜系统,用户输入可选菜id进行点菜: { Console.WriteLine(); Console.WriteLine("4 做个点菜系统,用户输入可选菜id进行点菜"); Console.WriteLine("*************输出菜单*************"); SingletonDishMenu.CreateDishMenu().ShowDish(); //Console.WriteLine("*************静态构造函数单例输出菜单*************"); //SingletonForStaticConstructor.GetDishMenu().ShowDish(); //Console.WriteLine("*************静态字段单例输出菜单*************"); //SingletonForStaticField.GetDishMenu().ShowDish(); Console.WriteLine("*************输入编号进行点菜,输入OK完成点菜*************"); Consumer consumer = new Consumer { Name = "cc" }; ConsumerContext consumerContext = new ConsumerContext { ConsumerName = consumer.Name, ConsumerTable = "001", CumsummerNumber = 2, AbstractFoodList = new List <AbstractFood>() }; consumer.Show(consumerContext); while (true) { Console.ForegroundColor = ConsoleColor.White; string userEnter = Console.ReadLine(); if (userEnter.ToUpper() == "OK") { break; } if (!ValidationHelper.ValidationUserEnter(userEnter, out UserEnter)) { continue; } AbstractFood baseDish = SimpleDishFactory.PointDish(UserEnter); if (baseDish == null) { Console.WriteLine("输入的编号不存在,请从新输入"); continue; } DishContext pointDishContext = new DishContext() { Id = baseDish.Id, ConsumerName = consumer.Name, TableNumber = consumerContext.ConsumerTable, Quantity = 1, HotType = "特辣" }; baseDish.PointDish(pointDishContext); var isAlready = consumerContext.AbstractFoodList.FirstOrDefault(x => x.Id == baseDish.Id); if (isAlready == null) { consumerContext.AbstractFoodList.Add(baseDish); } else { isAlready.DishContext.Quantity = isAlready.DishContext.Quantity + 1; } } Console.WriteLine($"*************{consumer.Name}先生/女士,你确认你的菜单:*************"); consumerContext.AbstractFoodList.ForEach(x => x.ConsumerConfirmDish()); } #endregion #region f)多线程演示:甲乙丙三个客人(三个线程)分别随机点5个菜,然后每个菜依次做菜、品尝、点评,最高的菜,展示出来 三个客人都吃完后,评选出得分最高的菜,展示出来 { TaskFactory taskFactory = new TaskFactory(); List <Task> taskList = new List <Task>(); List <Consumer> consumerList = new List <Consumer>(); Consumer consumerO = new Consumer { Name = "面向对象", PrintColor = ConsoleColor.DarkCyan }; consumerList.Add(consumerO); taskList.Add(taskFactory.StartNew(() => { ConsumerHelper.ConsumerIsComing(consumerO); })); Consumer consumerA = new Consumer { Name = "面向抽象", PrintColor = ConsoleColor.Blue }; consumerList.Add(consumerA); taskList.Add(taskFactory.StartNew(() => { ConsumerHelper.ConsumerIsComing(consumerA); })); Consumer consumerB = new Consumer { Name = "面向过程", PrintColor = ConsoleColor.Cyan }; consumerList.Add(consumerB); taskList.Add(taskFactory.StartNew(() => { ConsumerHelper.ConsumerIsComing(consumerB); })); taskFactory.ContinueWhenAll(taskList.ToArray(), (x) => { ConsumerHelper.PrintMostHighFood(consumerList); }); } #endregion Console.ReadKey(); }
public AfterCookDecorate(AbstractFood food) : base(food) { }
public WashFood(AbstractFood food) : base(food) { }
public AbstractServingFoodDecorator(AbstractFood abstractFood) : base(abstractFood) { }
public BaseFoodDecorate(AbstractFood food) { this._food = food; }
public BuyFood(AbstractFood food) : base(food) { }
public AbstractWashFoodDecorator(AbstractFood abstractFood) : base(abstractFood) { }
public CutFood(AbstractFood food) : base(food) { }
static void Main(string[] args) { #region 1.普通方法展示 { /* * 普通方法通过对象创建(NEW) * 引用左边是细节,右边也是细节(属于强依赖) */ //Console.WriteLine("**********Common method开始执行***********"); //AbstractFood hotBeefFood = new HotBeef(); //hotBeefFood.ShowMenuInfo(); //hotBeefFood.FoodTaste(); //hotBeefFood.FoodComment(); //AbstractFood eggplantFood = new Eggplant(); //eggplantFood.ShowMenuInfo(); //eggplantFood.FoodTaste(); //eggplantFood.FoodComment(); //AbstractFood toufuFood = new Toufu(); //toufuFood.ShowMenuInfo(); //toufuFood.FoodTaste(); //toufuFood.FoodComment(); //AbstractFood kungPaoChickenFood = new KungPaoChicken(); //kungPaoChickenFood.ShowMenuInfo(); //kungPaoChickenFood.FoodTaste(); //kungPaoChickenFood.FoodComment(); //Console.WriteLine("**********Common method 结束***********"); } #endregion #region 工厂方法展示 { #region 简单工厂 /* * 优点 * 缺点 */ //使用枚举值在简单工厂里面判断枚举值来创建对象 //AbstractFood abstractFood = SimpleFactoryCreate.CreateInstanceByNormal(SimpleFactoryCreate.SimpleFactorFoodType.Toufu); //abstractFood.ShowMenuInfo(); //abstractFood.FoodTaste(); //abstractFood.FoodComment(); //通过配置文件的枚举值来创建对象 //AbstractFood abstractFood = SimpleFactoryCreate.CreateTnstanceByNormalConfigure(); //abstractFood.ShowMenuInfo(); //abstractFood.FoodTaste(); //abstractFood.FoodComment(); //通过反射来创建对象 //AbstractFood abstactFactory = SimpleFactoryCreate.CreateInstance(); //abstactFactory.ShowMenuInfo(); //abstactFactory.FoodTaste(); //abstactFactory.FoodComment(); #endregion } { #region 工厂模式 /* * 优点:实现了开闭原则(开放扩展,封闭修改)。 * 缺点:如果要新建一种类就需要新建一个工厂 */ //BaseFactory baseFactory = new FactoryHotBeef(); //AbstractFood abstractFood = baseFactory.CreateInstance(); //abstractFood.ShowMenuInfo(); #endregion } { #region 抽象工厂 /* * 优点: * 缺点: */ //AbstractBaseFactory abstractBaseFactory = new SichuanCuisine(); //AbstractFood abstractFood = abstractBaseFactory.CeateChicken(); //abstractFood.ShowMenuInfo(); //abstractFood.FoodTaste(); //abstractFood.FoodComment(); #endregion } #endregion #region 单人 { //Console.WriteLine("*****************控制台点餐系统***********************"); //Console.WriteLine("********下面是我们的菜单,请选择要点菜的编号***********"); //Console.WriteLine("*************************************"); //#region 单例 菜单 SingleFoodMenu menu = SingleFoodMenu.CreateInstance(); if (menu != null && menu.foodList.Count() > 0) { foreach (var menuList in menu.foodList) { Console.WriteLine($"菜品编码[{menuList.FoodNo}] 菜品名称:{menuList.FoodName} 售价:{menuList.FoodPrice}"); } } ////string fileName = @"C:\Users\Administrator\source\repos\FoodMenuOrder\FoodMenuOrder\ConfigureFile\FoodMenu.xml";//文件名称与路径 ////using (Stream fStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite)) ////{ //// List<FoodModel> pList = FoodDataFactory.BuildProgrammerList(); //// XmlSerializer xmlFormat = new XmlSerializer(typeof(List<FoodModel>));//创建XML序列化器,需要指定对象的类型 //// xmlFormat.Serialize(fStream, pList); ////} ////using (Stream fStream = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite)) ////{ //// XmlSerializer xmlFormat = new XmlSerializer(typeof(List<FoodModel>));//创建XML序列化器,需要指定对象的类型 //// //使用XML反序列化对象 //// fStream.Position = 0;//重置流位置 //// List<FoodModel> pList = pList = (List<FoodModel>)xmlFormat.Deserialize(fStream); ////} //#endregion //"点餐".WriteLogConsole("Please input food id and press enter to continue...", "admin", ConsoleColor.Magenta); //while (true) //{ // if (!int.TryParse(Console.ReadLine(), out int input)) // { // "识别输入:".WriteLogConsole("非数字类型,请重新输入", "admin", ConsoleColor.Red); // } // else // { // var selectFood = menu.foodList.FirstOrDefault(c => c.FoodNo == input.ToString()); // if (selectFood == null) // { // "菜品选择:".WriteLogConsole("您选择的菜本店没有", "admin", ConsoleColor.Red); // } // else // { // "正确选择:".WriteLogConsole(string.Format("您当前点了编码{0}的【{1}】,价格{2}", selectFood.FoodNo, selectFood.FoodName, selectFood.FoodPrice), "root", ConsoleColor.Gray); // AbstractFood abstractFood = SimpleFactoryCreate.CreateInstanceByNormal((SimpleFactoryCreate.SimpleFactorFoodType)Enum.Parse(typeof(SimpleFactoryCreate.SimpleFactorFoodType), selectFood.FoodNo)); // abstractFood.ShowMenuInfo(); // abstractFood.FoodTaste(); // abstractFood.CookingFood(abstractFood.foodBaseModel.FirstOrDefault()); // } // } //} #region 多人订购 { //Read the XML load configuration //showMenu CustomerList customerList = SingleCustomer.CreateInstance()._CustomerList; Console.WriteLine($"{string.Join(",", customerList.name)}前来点餐"); List <Task> tasks = new List <Task>(); Dictionary <string, Dictionary <AbstractFood, int> > dicAll = new Dictionary <string, Dictionary <AbstractFood, int> >(); List <Dictionary <AbstractFood, int> > dicList = new List <Dictionary <AbstractFood, int> >(); foreach (var customerItem in customerList.name) { dicList.Add(new Dictionary <AbstractFood, int>()); } int k = 0; //遍历所有顾客 foreach (var item in customerList.name) { Dictionary <AbstractFood, int> foodDic = dicList[k++]; tasks.Add(Task.Run(() => { //随机点5个菜 List <FoodModel> list = menu.foodList.GetFoodListByRandom(); "已点菜单".WriteLogConsole($"客人{item},已点{string.Join(",", list.Select(s => s.FoodName))}", "shsjj", ConsoleColor.Red); foreach (var foodList in list) { "开始烹饪:".WriteLogConsole($"菜名:{foodList.FoodName}即将开始:", "admin", ConsoleColor.Yellow); //依次做菜、尝、点评 AbstractFood abstractFood = SimpleFactoryCreate.CreateInstanceByAssembly(foodList.AssemblyPath); abstractFood.CookingFood(foodList); abstractFood.FoodTaste(); int score = abstractFood.FoodComment(); foodDic.Add(abstractFood, score); } dicAll.Add(item, foodDic); int foodMaxScore = foodDic.Values.Max();//获取字典内的最大分数值 //循环 查找字典内 值为最大分数的(有可能最大分数有多个) foreach (var maxScoreItem in foodDic.Where(d => d.Value == foodMaxScore)) { Console.WriteLine($"{item}点餐中,最高分食物是{maxScoreItem.Key.foodBaseModel[0].FoodName},最高分为{maxScoreItem.Value}"); } })); //可以 每个线程把最高分返回回来 } Task.WaitAll(tasks.ToArray()); //一定要等客人都吃完 Console.WriteLine("*********************************"); int maxAll = dicList.Max(d => d.Values.Max()); for (int i = 0; i < customerList.name.Count; i++) { var dic = dicList[i]; foreach (var item in dic.Where(d => d.Value == maxAll)) { Console.WriteLine($"{customerList.name[i]}最高分食物是{item.Key.foodBaseModel[0].FoodName},分数为{item.Value}"); } } } #endregion } #endregion Console.Read(); }
public BaseFoodDecorator(AbstractFood food) : base() { this._food = food; }
public BeforeCookDecorate(AbstractFood food) : base(food) { }
public ServedFood(AbstractFood food) : base(food) { }
abstract protected bool canProcess(AbstractFood food); // Check if we can cook/slice/spice.