Привет
Я сделал тестовое задание, хотел бы попросить поревьюить код, что бы его улучшить.
Нужно: - улучшить архитектуру: изменить модель данных, правильно разбить код на файлы - полностью развязать модель и UI - внедрить другие паттерны проектирования - внедрить MVC (если нужно)
Задание 3. Модель автоматического аппарата быстрого питания. Необходимо выполнить реализацию задачи с максимальным использованием преимуществ объектно-ориентированного подхода и, по возможности, реализовать подходящие архитектурные шаблоны проектирования приложений. В качестве результата нужно предоставить UML-диаграмму классов предметной области или приложение реализующее работу вышеупомянутого аппарата или и то и другое. Создать объектную модель аппарата по быстрому приготовлению напитков и еды со следующими допущениями:
- Латте – это эспрессо + молоко
- Капучино – эспрессо + молоко + молочная пенка
- Молоко можно добавлять к следующим напиткам: эспрессо, латте, чай черный, чай зеленый
- Сахар можно добавлять ко всем напиткам. Количество порций сахара указывается пользователем (от 0 до 5).
- Ветчину, сыр можно добавлять к хлебу и булочке (получается бутерброд)
- Комплекс – это набор из напитка и еды по фиксированной цене. При этом можно выбрать любой элемент из категории «Напиток» + один элемент из «Добавки к напиткам», аналогично с едой: 1 элемент из категории «Еда» + 1 элемент из категории «Добавки к еде». Задание.
- Аппарат должен считать стоимость выбранного заказа и выводить в окно со стоимостью.
После нажатия на кнопку выдать, в диалоговом окне выводить строку с составом заказа, например, Капучино (Эспрессо+Молоко+Сахар) Бутерброд (Хлеб+Ветчина). В случае реализации приложения учитывать следующее ограничение: Язык реализации: C# Уровень представления: Windows Forms или Web-приложение
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using static WindowsFormsApp1.CoffeeMachine; namespace WindowsFormsApp1 { public partial class Form1 : Form { private CoffeeMachine coffeeMachine = new CoffeeMachine(); public Form1() { InitializeComponent(); Init(); } private void Init() { radioButtonEspresso.Text = new Espresso().Name + new Espresso().GetCost() + " руб"; radioButtonLatte.Text = "Латте - " + coffeeMachine.GetLatte().GetCost() + " руб"; radioButtonCapuchino.Text = "Капуччино - " + coffeeMachine.GetCapuchino().GetCost() + " руб"; radioButtonBlackTea.Text = new BlackTea().Name + new BlackTea().GetCost() + " руб"; radioButtonGreenTea.Text = new GreenTea().Name + new GreenTea().GetCost() + " руб"; radioButtonWater.Text = new Water().Name + new Water().GetCost() + " руб"; radioButtonBread.Text = new Bread().Name + new Bread().GetCost() + " руб"; radioButtonRoll.Text = new Roll().Name + new Roll().GetCost() + " руб"; radioButtonChips.Text = new Chips().Name + new Chips().GetCost() + " руб"; radioButtonCookie.Text = new Cookie().Name + new Cookie().GetCost() + " руб"; Meals blankObject = new Espresso(); checkBoxMilk.Text = new Milk(blankObject).Name + new Milk(blankObject).Cost; checkBoxSugar.Text = new Sugar(blankObject).Name + new Sugar(blankObject).Cost; checkBoxSyrop.Text = new Syrop(blankObject).Name + new Syrop(blankObject).Cost; checkBoxHam.Text = new Ham(blankObject).Name + new Ham(blankObject).Cost; checkBoxCheese.Text = new Cheese(blankObject).Name + new Cheese(blankObject).Cost; checkBoxJam.Text = new Jam(blankObject).Name + new Jam(blankObject).Cost; checkBoxComplex.Text = "Комплекс (1 напиток с любой добавкой + 1 еда с любой добавкой на выбор)"; labelComplexCost.Text = "90 руб"; radioButtonBread.Checked = true; } private void ShowCost(int cost) { textBoxCost.Text = cost.ToString(); } private void RecountMealsCost() { Dictionary<Meals, bool> beverageChoice = new Dictionary<Meals, bool>() { {new Espresso(), radioButtonEspresso.Checked}, {coffeeMachine.GetLatte(), radioButtonLatte.Checked}, {coffeeMachine.GetCapuchino(), radioButtonCapuchino.Checked }, {new BlackTea(), radioButtonBlackTea.Checked}, {new GreenTea(), radioButtonGreenTea.Checked}, {new Water(), radioButtonWater.Checked } }; RecountBeverageCost(beverageChoice.FirstOrDefault(x => x.Value == true).Key); Dictionary<Meals, bool> foodChoice = new Dictionary<Meals, bool>() { { new Bread(), radioButtonBread.Checked}, { new Roll(), radioButtonRoll.Checked}, { new Chips(), radioButtonChips.Checked}, { new Cookie(), radioButtonCookie.Checked} }; RecountFoodCost(foodChoice.FirstOrDefault(x => x.Value == true).Key); int totalCost = coffeeMachine.BeverageCost + coffeeMachine.FoodCost; ShowCost(totalCost); buttonGiveOrder.Enabled = coffeeMachine.IsComplexOrderEnabled(checkBoxComplex.Checked, totalCost); } private void RecountBeverageCost(Meals meal) { if (meal.GetType().Name != "Milk") { meal = coffeeMachine.AddAdditionIfChecked(checkBoxMilk.Checked, meal, new Milk(meal)); checkBoxMilk.Enabled = true; } else { checkBoxMilk.Enabled = false; } for (int i = 0; i < numericUpDownSugarPieces.Value; i++) { meal = coffeeMachine.AddAdditionIfChecked(checkBoxSugar.Checked, meal, new Sugar(meal)); } meal = coffeeMachine.AddAdditionIfChecked(checkBoxSyrop.Checked, meal, new Syrop(meal)); coffeeMachine.BeverageCost = meal.GetCost(); } private void RecountFoodCost(Meals meal) { if (meal.GetType().Name == "Bread" || meal.GetType().Name == "Roll") { meal = coffeeMachine.AddAdditionIfChecked(checkBoxHam.Checked, meal, new Ham(meal)); meal = coffeeMachine.AddAdditionIfChecked(checkBoxCheese.Checked, meal, new Cheese(meal)); checkBoxHam.Enabled = true; checkBoxCheese.Enabled = true; } else { checkBoxHam.Enabled = false; checkBoxCheese.Enabled = false; } meal = coffeeMachine.AddAdditionIfChecked(checkBoxJam.Checked, meal, new Jam(meal)); coffeeMachine.FoodCost = meal.GetCost(); } private void radioButton_Clicked(object sender, EventArgs e) { RecountMealsCost(); } private void numericUpDown1_ValueChanged(object sender, EventArgs e) { RecountMealsCost(); } private void checkBox_CheckedChanged(object sender, EventArgs e) { RecountMealsCost(); } private void button1_Click(object sender, EventArgs e) { string caption = new Order().GetInfo(groupBox1, groupBox2, groupBox3, groupBox4).Caption; string message = new Order().GetInfo(groupBox1, groupBox2, groupBox3, groupBox4).Message; MessageBox.Show(caption, message, MessageBoxButtons.OK); } } } using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WindowsFormsApp1 { public class CoffeeMachine { public int BeverageCost { get; set; } public int FoodCost { get; set; } private int complexCost = 90; public abstract class Meals { public Meals(string name) { this.Name = name; } public string Name { get; protected set; } public abstract int GetCost(); } public class Espresso : Meals { public Espresso() : base("Эспрессо - ") { } public override int GetCost() { return 60; } } public class BlackTea : Meals { public BlackTea() : base("Чёрный чай - ") { } public override int GetCost() { return 25; } } public class GreenTea : Meals { public GreenTea() : base("Зелёный чай - ") { } public override int GetCost() { return 25; } } public class Water : Meals { public Water() : base("Вода - ") { } public override int GetCost() { return 20; } } public abstract class MealsDecorator : Meals { protected Meals meals; protected int cost; protected string name; public MealsDecorator(string name, Meals meals) : base(name) { this.meals = meals; } } public class Milk : MealsDecorator { public Milk(Meals meals) : base(meals.Name, meals) { } public string Name { get; set; } = "Молоко - "; public int Cost { get; set; } = 10; public override int GetCost() { return meals.GetCost() + Cost; } } public class MilkFroth : MealsDecorator { public MilkFroth(Meals meals) : base(meals.Name + "Молочная пенка - ", meals) { } public override int GetCost() { this.cost = 10; return meals.GetCost() + this.cost; } } public class Syrop : MealsDecorator { public Syrop(Meals meals) : base(meals.Name, meals) { } public string Name { get; set; } = "Сироп - "; public int Cost { get; set; } = 5; public override int GetCost() { return meals.GetCost() + Cost; } } public class Sugar : MealsDecorator { public Sugar(Meals meals) : base(meals.Name, meals) { } public string Name { get; set; } = "Сахар - "; public int Cost { get; set; } = 5; public override int GetCost() { return meals.GetCost() + Cost; } } public class Ham : MealsDecorator { public Ham(Meals meals) : base(meals.Name, meals) { } public string Name { get; set; } = "Ветчина - "; public int Cost { get; set; } = 15; public override int GetCost() { return meals.GetCost() + Cost; } } public class Cheese : MealsDecorator { public Cheese(Meals meals) : base(meals.Name, meals) { } public string Name { get; set; } = "Сыр - "; public int Cost { get; set; } = 10; public override int GetCost() { return meals.GetCost() + Cost; } } public class Jam : MealsDecorator { public Jam(Meals meals) : base(meals.Name, meals) { } public string Name { get; set; } = "Джем - "; public int Cost { get; set; } = 7; public override int GetCost() { return meals.GetCost() + Cost; } } public Meals GetLatte() { return new Milk(new Espresso()); } public Meals GetCapuchino() { return new MilkFroth(new Milk(new Espresso())); } public class Bread : Meals { public Bread() : base("Хлеб - ") { } public override int GetCost() { return 10; } } public class Roll : Meals { public Roll() : base("Булочка - ") { } public override int GetCost() { return 15; } } public class Chips : Meals { public Chips() : base("Чипсы - ") { } public override int GetCost() { return 34; } } public class Cookie : Meals { public Cookie() : base("Печенье - ") { } public override int GetCost() { return 29; } } public Meals AddAdditionIfChecked(bool isControlChecked, Meals meal, MealsDecorator decorator) { if (isControlChecked) { meal = decorator; } return meal; } public bool IsComplexOrderEnabled(bool controlStateToEnable, int cost) { if (controlStateToEnable == true && cost > complexCost) return false; return true; } } } using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WindowsFormsApp1 { class Order { public string BeverageName { get; set; } public string[] BeverageAdditionsNames { get; set; } public string FoodName { get; set; } public string[] FoodAdditionsNames { get; set; } public Order(string beverageName, string[] beverageAdditionsNames, string foodName, string[] foodAdditionsNames) { BeverageName = beverageName; FoodName = foodName; BeverageAdditionsNames = beverageAdditionsNames; FoodAdditionsNames = foodAdditionsNames; } public string Message { get; set; } public string Caption { get; set; } public Order(string message, string caption) { Message = message; Caption = caption; } public Order() { } public Order Get<T1, T2, T3>(T3 beverages, T3 beverageAdditions, T3 foods, T3 foodAdditions) where T1: RadioButton where T2: CheckBox where T3: GroupBox { Func<Control, string> GetName = x => { return x.Text.Split(new string[] {" -"}, StringSplitOptions.None)[0]; }; Func<T1, bool> RadiobuttonChecked = x => { return x.Checked == true; }; Func<T2, bool> CheckboxChecked = x => { return x.Checked == true; }; Func<T2, bool> CheckboxEnabled = x => { return x.Enabled == true; }; var beverage = GetControls<T1>(beverages).Where(RadiobuttonChecked).Select(GetName).SingleOrDefault(); var beverageAddition = GetControls<T2>(beverageAdditions).Where(CheckboxChecked).Select(GetName).ToArray(); var food = GetControls<T1>(foods).Where(RadiobuttonChecked).Select(GetName).SingleOrDefault(); var foodAddition = GetControls<T2>(foodAdditions).Where(CheckboxChecked).Where(CheckboxEnabled).Select(GetName).ToArray(); return new Order(beverage, beverageAddition, food, foodAddition); } private IEnumerable<T> GetControls<T>(GroupBox source) { return source.Controls.OfType<T>(); } public Order GetInfo<T>(T beverages, T beverageAdditions, T foods, T foodAdditions) where T: GroupBox { Order order = Get<RadioButton, CheckBox, GroupBox>(beverages, beverageAdditions, foods, foodAdditions); string beverageDelimiter = ", "; string foodDelimiter = beverageDelimiter; string additionsDelimeter = beverageDelimiter; var chosenBeverageAdditions = string.Join(beverageDelimiter, order.BeverageAdditionsNames); var chosenFoodAdditions = string.Join(foodDelimiter, order.FoodAdditionsNames); if (chosenBeverageAdditions == string.Empty) beverageDelimiter = null; if (chosenFoodAdditions == string.Empty) foodDelimiter = null; string caption = "Заказ"; string message = "Напиток: " + order.BeverageName + beverageDelimiter + chosenBeverageAdditions + "\n" + "Еда: " + order.FoodName + foodDelimiter + chosenFoodAdditions; return new Order(caption, message); } } }