Лабораторная работа №4

This commit is contained in:
Anitonchik 2024-04-02 09:21:14 +04:00
parent 290f64ed48
commit 7719d789d9
7 changed files with 484 additions and 49 deletions

View File

@ -74,6 +74,7 @@ public abstract class AbstractCompany
return company._collection.Remove(position);
}
/// <summary>
/// Получение случайного объекта из коллекции
/// </summary>

View File

@ -0,0 +1,27 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectDumpTruck.CollectionGenericObjects;
/// <summary>
/// Тип коллекции
/// </summary>
public enum CollectionType
{
/// <summary>
/// Неопределено
/// </summary>
None = 0,
/// <summary>
/// Массив
/// </summary>
Massive = 1,
/// <summary>
/// Список
/// </summary>
List = 2
}

View File

@ -0,0 +1,96 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectDumpTruck.CollectionGenericObjects;
/// <summary>
/// Параметризованный набор объектов
/// </summary>
/// <typeparam name="T">Параметр: ограничение - ссылочный тип</typeparam>
public class ListGenericObjects<T> : ICollectionGenericObjects<T>
where T : class
{
/// <summary>
/// Список объектов, которые храним
/// </summary>
private readonly List<T?> _collection;
/// <summary>
/// Максимально допустимое число объектов в списке
/// </summary>
private int _maxCount;
public int Count => _collection.Count;
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } }
/// <summary>
/// Конструктор
/// </summary>
public ListGenericObjects()
{
_collection = new();
}
public T? Get(int position)
{
if (position >= 0 && position < Count && _collection[position] != null)
return _collection[position];
return null;
}
public int Insert(T obj)
{
// TODO проверка, что не превышено максимальное количество элементов
// TODO вставка в конец набора
if (_collection.Count > _maxCount)
{
return -1;
}
_collection.Add(obj);
return _collection.Count;
}
public int Insert(T obj, int position)
{
// TODO проверка, что не превышено максимальное количество элементов
// TODO проверка позиции
// TODO вставка по позиции
if (_collection.Count > _maxCount || position < 0 || position > _maxCount)
{
return -1;
}
if (_collection[position] == null)
{
_collection.Insert(position, obj);
return position;
}
for (int i = position + 1; i < _maxCount; ++i)
{
if (_collection[i] == null)
{
_collection.Insert(position, obj);
return position;
}
}
for (int i = 0; i < position; ++i)
{
if (_collection[i] == null)
{
_collection.Insert(position, obj);
return position;
}
}
return -1;
}
public T Remove(int position)
{
// TODO проверка позиции
// TODO удаление объекта из списка
if (position < 0 || position > _maxCount)
{
return null;
}
T temp = _collection[position];
_collection.RemoveAt(position);
return temp;
}
}

View File

@ -0,0 +1,91 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectDumpTruck.CollectionGenericObjects;
/// <summary>
/// Класс-хранилище коллекций
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : class
{
/// <summary>
/// Словарь (хранилище) с коллекциями
/// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
/// <summary>
/// Возвращение списка названий коллекций
/// </summary>
public List<string> Keys => _storages.Keys.ToList();
/// <summary>
/// Конструктор
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
}
/// <summary>
/// Добавление коллекции в хранилище
/// </summary>
/// <param name="name">Название коллекции</param>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
{
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом
// TODO Прописать логику для добавления
if (_storages.ContainsKey(name))
{
return;
}
switch (collectionType)
{
case CollectionType.None:
return;
case CollectionType.Massive:
_storages.Add(name, new MassiveGenericObjects<T>());
break;
case CollectionType.List:
_storages.Add(name, new ListGenericObjects<T>());
break;
}
}
/// <summary>
/// Удаление коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
public void DelCollection(string name)
{
// TODO Прописать логику для удаления коллекции
/*if (name == null)
return;*/
if ( _storages.ContainsKey(name))
{
_storages.Remove(name);
}
}
/// <summary>
/// Доступ к коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
/// <returns></returns>
public ICollectionGenericObjects<T>? this[string name]
{
get
{
// TODO Продумать логику получения объекта
if (_storages.ContainsKey(name))
{
return _storages[name];
}
return null;
}
}
}

View File

@ -29,38 +29,82 @@
private void InitializeComponent()
{
groupBoxTools = new GroupBox();
panelCompanyTools = new Panel();
buttonAddTruck = new Button();
buttonAddDumpTruck = new Button();
buttonRefresh = new Button();
maskedTextBoxPosition = new MaskedTextBox();
buttonGoToChek = new Button();
buttonRemoveTruck = new Button();
maskedTextBoxPosition = new MaskedTextBox();
buttonAddDumpTruck = new Button();
buttonAddTruck = new Button();
buttonCreateCompany = new Button();
panelStorage = new Panel();
buttonCollectionDel = new Button();
listBoxCollection = new ListBox();
buttonCollectionAdd = new Button();
radioButtonList = new RadioButton();
radioButtonMassive = new RadioButton();
textBoxCollectionName = new TextBox();
labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
SuspendLayout();
//
// groupBoxTools
//
groupBoxTools.Controls.Add(buttonRefresh);
groupBoxTools.Controls.Add(buttonGoToChek);
groupBoxTools.Controls.Add(buttonRemoveTruck);
groupBoxTools.Controls.Add(maskedTextBoxPosition);
groupBoxTools.Controls.Add(buttonAddDumpTruck);
groupBoxTools.Controls.Add(buttonAddTruck);
groupBoxTools.Controls.Add(panelCompanyTools);
groupBoxTools.Controls.Add(buttonCreateCompany);
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(832, 0);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(250, 753);
groupBoxTools.Size = new Size(250, 827);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonAddTruck);
panelCompanyTools.Controls.Add(buttonAddDumpTruck);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
panelCompanyTools.Controls.Add(buttonGoToChek);
panelCompanyTools.Controls.Add(buttonRemoveTruck);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Location = new Point(3, 450);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(244, 374);
panelCompanyTools.TabIndex = 4;
//
// buttonAddTruck
//
buttonAddTruck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddTruck.Location = new Point(15, 13);
buttonAddTruck.Name = "buttonAddTruck";
buttonAddTruck.Size = new Size(220, 57);
buttonAddTruck.TabIndex = 1;
buttonAddTruck.Text = "Добавление грузовика";
buttonAddTruck.UseVisualStyleBackColor = true;
buttonAddTruck.Click += ButtonAddTruck_Click;
//
// buttonAddDumpTruck
//
buttonAddDumpTruck.Location = new Point(15, 76);
buttonAddDumpTruck.Name = "buttonAddDumpTruck";
buttonAddDumpTruck.Size = new Size(220, 57);
buttonAddDumpTruck.TabIndex = 2;
buttonAddDumpTruck.Text = "Добавление самосвала";
buttonAddDumpTruck.UseVisualStyleBackColor = true;
buttonAddDumpTruck.Click += ButtonAddDumpTruck_Click;
//
// buttonRefresh
//
buttonRefresh.Location = new Point(18, 507);
buttonRefresh.Location = new Point(15, 300);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(220, 57);
buttonRefresh.TabIndex = 7;
@ -68,9 +112,18 @@
buttonRefresh.UseVisualStyleBackColor = true;
buttonRefresh.Click += ButtonRefresh_Click;
//
// maskedTextBoxPosition
//
maskedTextBoxPosition.Location = new Point(15, 139);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(223, 27);
maskedTextBoxPosition.TabIndex = 4;
maskedTextBoxPosition.ValidatingType = typeof(int);
//
// buttonGoToChek
//
buttonGoToChek.Location = new Point(18, 406);
buttonGoToChek.Location = new Point(15, 237);
buttonGoToChek.Name = "buttonGoToChek";
buttonGoToChek.Size = new Size(220, 57);
buttonGoToChek.TabIndex = 6;
@ -80,7 +133,7 @@
//
// buttonRemoveTruck
//
buttonRemoveTruck.Location = new Point(18, 309);
buttonRemoveTruck.Location = new Point(15, 174);
buttonRemoveTruck.Name = "buttonRemoveTruck";
buttonRemoveTruck.Size = new Size(220, 57);
buttonRemoveTruck.TabIndex = 5;
@ -88,35 +141,97 @@
buttonRemoveTruck.UseVisualStyleBackColor = true;
buttonRemoveTruck.Click += ButtonRemoveTruck_Click;
//
// maskedTextBoxPosition
// buttonCreateCompany
//
maskedTextBoxPosition.Location = new Point(18, 276);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(226, 27);
maskedTextBoxPosition.TabIndex = 4;
maskedTextBoxPosition.ValidatingType = typeof(int);
buttonCreateCompany.Location = new Point(18, 406);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(220, 29);
buttonCreateCompany.TabIndex = 9;
buttonCreateCompany.Text = "Создать компанию";
buttonCreateCompany.UseVisualStyleBackColor = true;
buttonCreateCompany.Click += ButtonCreateCompany_Click;
//
// buttonAddDumpTruck
// panelStorage
//
buttonAddDumpTruck.Location = new Point(18, 173);
buttonAddDumpTruck.Name = "buttonAddDumpTruck";
buttonAddDumpTruck.Size = new Size(220, 57);
buttonAddDumpTruck.TabIndex = 2;
buttonAddDumpTruck.Text = "Добавление самосвала";
buttonAddDumpTruck.UseVisualStyleBackColor = true;
buttonAddDumpTruck.Click += ButtonAddDumpTruck_Click;
panelStorage.Controls.Add(buttonCollectionDel);
panelStorage.Controls.Add(listBoxCollection);
panelStorage.Controls.Add(buttonCollectionAdd);
panelStorage.Controls.Add(radioButtonList);
panelStorage.Controls.Add(radioButtonMassive);
panelStorage.Controls.Add(textBoxCollectionName);
panelStorage.Controls.Add(labelCollectionName);
panelStorage.Dock = DockStyle.Top;
panelStorage.Location = new Point(3, 23);
panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(244, 310);
panelStorage.TabIndex = 8;
//
// buttonAddTruck
// buttonCollectionDel
//
buttonAddTruck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddTruck.Location = new Point(18, 110);
buttonAddTruck.Name = "buttonAddTruck";
buttonAddTruck.Size = new Size(220, 57);
buttonAddTruck.TabIndex = 1;
buttonAddTruck.Text = "Добавление грузовика";
buttonAddTruck.UseVisualStyleBackColor = true;
buttonAddTruck.Click += ButtonAddTruck_Click;
buttonCollectionDel.Location = new Point(3, 265);
buttonCollectionDel.Name = "buttonCollectionDel";
buttonCollectionDel.Size = new Size(238, 29);
buttonCollectionDel.TabIndex = 6;
buttonCollectionDel.Text = "Удалить коллекцию";
buttonCollectionDel.UseVisualStyleBackColor = true;
buttonCollectionDel.Click += ButtonCollectionDel_Click;
//
// listBoxCollection
//
listBoxCollection.FormattingEnabled = true;
listBoxCollection.ItemHeight = 20;
listBoxCollection.Location = new Point(3, 135);
listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(238, 124);
listBoxCollection.TabIndex = 5;
//
// buttonCollectionAdd
//
buttonCollectionAdd.Location = new Point(3, 100);
buttonCollectionAdd.Name = "buttonCollectionAdd";
buttonCollectionAdd.Size = new Size(238, 29);
buttonCollectionAdd.TabIndex = 4;
buttonCollectionAdd.Text = "Добавить коллекцию";
buttonCollectionAdd.UseVisualStyleBackColor = true;
buttonCollectionAdd.Click += ButtonCollectionAdd_Click;
//
// radioButtonList
//
radioButtonList.AutoSize = true;
radioButtonList.Location = new Point(142, 70);
radioButtonList.Name = "radioButtonList";
radioButtonList.Size = new Size(80, 24);
radioButtonList.TabIndex = 3;
radioButtonList.TabStop = true;
radioButtonList.Text = "Список";
radioButtonList.UseVisualStyleBackColor = true;
//
// radioButtonMassive
//
radioButtonMassive.AutoSize = true;
radioButtonMassive.Location = new Point(15, 70);
radioButtonMassive.Name = "radioButtonMassive";
radioButtonMassive.Size = new Size(82, 24);
radioButtonMassive.TabIndex = 2;
radioButtonMassive.TabStop = true;
radioButtonMassive.Text = "Массив";
radioButtonMassive.UseVisualStyleBackColor = true;
//
// textBoxCollectionName
//
textBoxCollectionName.Location = new Point(3, 37);
textBoxCollectionName.Name = "textBoxCollectionName";
textBoxCollectionName.Size = new Size(238, 27);
textBoxCollectionName.TabIndex = 1;
//
// labelCollectionName
//
labelCollectionName.AutoSize = true;
labelCollectionName.Location = new Point(38, 14);
labelCollectionName.Name = "labelCollectionName";
labelCollectionName.Size = new Size(155, 20);
labelCollectionName.TabIndex = 0;
labelCollectionName.Text = "Название коллекции";
//
// comboBoxSelectorCompany
//
@ -124,7 +239,7 @@
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
comboBoxSelectorCompany.Location = new Point(18, 26);
comboBoxSelectorCompany.Location = new Point(18, 353);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(220, 28);
comboBoxSelectorCompany.TabIndex = 0;
@ -135,7 +250,7 @@
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(832, 753);
pictureBox.Size = new Size(832, 827);
pictureBox.TabIndex = 3;
pictureBox.TabStop = false;
//
@ -143,13 +258,16 @@
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1082, 753);
ClientSize = new Size(1082, 827);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Name = "FormTruckCollection";
Text = "Коллекция грузовиков";
groupBoxTools.ResumeLayout(false);
groupBoxTools.PerformLayout();
panelCompanyTools.ResumeLayout(false);
panelCompanyTools.PerformLayout();
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
ResumeLayout(false);
}
@ -165,5 +283,15 @@
private PictureBox pictureBox;
private Button buttonRefresh;
private Button buttonGoToChek;
private Panel panelStorage;
private RadioButton radioButtonList;
private RadioButton radioButtonMassive;
private TextBox textBoxCollectionName;
private Label labelCollectionName;
private Button buttonCollectionAdd;
private Button buttonCreateCompany;
private Button buttonCollectionDel;
private ListBox listBoxCollection;
private Panel panelCompanyTools;
}
}

View File

@ -14,6 +14,10 @@ namespace ProjectDumpTruck;
public partial class FormTruckCollection : Form
{
/// <summary>
/// Хранилише коллекций
/// </summary>
private readonly StorageCollection<DrawningTruck> _storageCollection;
/// <summary>
/// Компания
@ -23,22 +27,17 @@ public partial class FormTruckCollection : Form
public FormTruckCollection()
{
InitializeComponent();
_storageCollection = new();
}
/// <summary>
/// Выбор компании
/// </summary>
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ComboBoxSelectorCompany_SelectedIndexChanged(object sender, EventArgs e)
{
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new TruckSharingService(pictureBox.Width,
pictureBox.Height, new MassiveGenericObjects<DrawningTruck>());
break;
}
panelCompanyTools.Enabled = true;
}
@ -181,5 +180,95 @@ public partial class FormTruckCollection : Form
}
pictureBox.Image = _company.Show();
}
/// <summary>
/// Добавление коллекции
/// </summary>
/// <param name="sender"></par
private void ButtonCollectionAdd_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxCollectionName.Text) || (!radioButtonList.Checked && !radioButtonMassive.Checked))
{
MessageBox.Show("Не все данные заполнены", "Ошибка",
MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
CollectionType collectionType = CollectionType.None;
if (radioButtonMassive.Checked)
{
collectionType = CollectionType.Massive;
}
else if (radioButtonList.Checked)
{
collectionType = CollectionType.List;
}
_storageCollection.AddCollection(textBoxCollectionName.Text, collectionType);
RerfreshListBoxItems();
}
/// <summary>
/// Обновление списка в listBoxCollection
/// </summary>
private void RerfreshListBoxItems()
{
listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
string? colName = _storageCollection.Keys?[i];
if (!string.IsNullOrEmpty(colName))
{
listBoxCollection.Items.Add(colName);
}
}
}
private void ButtonCollectionDel_Click(object sender, EventArgs e)
{
// TODO прописать логику удаления элемента из коллекции
// нужно убедиться, что есть выбранная коллекция
// спросить у пользователя через MessageBox, что он подтверждает, что хочет удалить запись
// удалить и обновить ListBox
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItems == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
{
return;
}
_storageCollection.DelCollection(listBoxCollection.SelectedItem.ToString());
RerfreshListBoxItems();
}
/// <summary>
/// Создание компании
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonCreateCompany_Click(object sender, EventArgs e)
{
if (listBoxCollection.SelectedIndex < 0 || listBoxCollection.SelectedItem == null)
{
MessageBox.Show("Коллекция не выбрана");
return;
}
ICollectionGenericObjects<DrawningTruck>? collection =
_storageCollection[listBoxCollection.SelectedItem.ToString() ?? string.Empty];
if (collection == null)
{
MessageBox.Show("Коллекция не проинициализирована");
return;
}
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new TruckSharingService(pictureBox.Width,
pictureBox.Height, collection);
break;
}
panelCompanyTools.Enabled = true;
RerfreshListBoxItems();
}
}

View File

@ -117,4 +117,7 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="buttonRefresh.Locked" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>True</value>
</metadata>
</root>