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

This commit is contained in:
5_fG 2024-06-05 18:16:12 +04:00
parent 3139efc43b
commit c7a6718b99
13 changed files with 396 additions and 45 deletions

View File

@ -59,7 +59,7 @@ public abstract class AbstractCompany
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningTrackedVehicle excavator)
{
return company._collection.Insert(excavator);
return company._collection.Insert(excavator, new DrawningTrackedVehicleEqutables());
}
/// <summary>
@ -103,6 +103,12 @@ public abstract class AbstractCompany
return bitmap;
}
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningTrackedVehicle?> comparer) => _collection?.CollectionSort(comparer);
/// <summary>
/// Вывод заднего фона
/// </summary>

View File

@ -0,0 +1,76 @@
namespace ProjectExcavator.CollectionGenericObjects;
/// <summary>
/// Класс, хранящиий информацию по коллекции
/// </summary>
public class CollectionInfo : IEquatable<CollectionInfo>
{
/// <summary>
/// Название
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Тип
/// </summary>
public CollectionType CollectionType { get; private set; }
/// <summary>
/// Описание
/// </summary>
public string Description { get; private set; }
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separator = "-";
/// <summary>
/// Конструктор
/// </summary>
/// <param name="name">Название</param>
/// <param name="collectionType">Тип</param>
/// <param name="description">Описание</param>
public CollectionInfo(string name, CollectionType collectionType, string description)
{
Name = name;
CollectionType = collectionType;
Description = description;
}
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="data">Строка</param>
/// <returns>Объект или null</returns>
public static CollectionInfo? GetCollectionInfo(string data)
{
string[] strs = data.Split(_separator, StringSplitOptions.RemoveEmptyEntries);
if (strs.Length < 1 || strs.Length > 3)
{
return null;
}
return new CollectionInfo(strs[0], (CollectionType)Enum.Parse(typeof(CollectionType), strs[1]), strs.Length > 2 ? strs[2] : string.Empty);
}
public override string ToString()
{
return Name + _separator + CollectionType + _separator + Description;
}
public bool Equals(CollectionInfo? other)
{
return Name == other?.Name;
}
public override bool Equals(object? obj)
{
return Equals(obj as CollectionInfo);
}
public override int GetHashCode()
{
return Name.GetHashCode();
}
}

View File

@ -21,16 +21,18 @@ public interface ICollectionGenericObjects<T>
/// Добавление объекта в коллекцию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <param name="comparer">Сравнение двух объектов</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj);
int Insert(T obj, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Добавление объекта в коллекцию на конкретную позицию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param>
/// <param name="comparer">Сравнение двух объектов</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, int position);
int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
@ -56,4 +58,10 @@ public interface ICollectionGenericObjects<T>
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
}

View File

@ -48,7 +48,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj,IEqualityComparer<T?>? comparer = null)
{
//проверка, что не превышено максимальное количество элементов
//вставка в конец набора
@ -57,12 +57,16 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
{
throw new CollectionOverflowException();
}
if (_collection.Contains(obj, comparer))
{
throw new ObjectExistsException();
}
_collection.Add(obj);
return 1;
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
// проверка, что не превышено максимальное количество элементов
// проверка позиции
@ -76,6 +80,10 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
{
throw new PositionOutOfCollectionException();
}
if (_collection.Contains(obj, comparer))
{
throw new ObjectExistsException(position);
}
_collection.Insert(position, obj);
return 1;
}
@ -100,4 +108,9 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}

View File

@ -1,4 +1,5 @@
using ProjectExcavator.Exceptions;
namespace ProjectExcavator.CollectionGenericObjects;
/// <summary>
@ -61,14 +62,18 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
//Вставка в свободное место набора
int index = Array.IndexOf(_collection, null);
if (_collection.Contains(obj, comparer))
{
throw new ObjectExistsException(index);
}
return Insert(obj, 0);
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
//Проверка позиции
//Проверка, что элемент массива по этой позиции пустой, если нет, то
@ -77,6 +82,11 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection.Contains(obj, comparer))
{
throw new ObjectExistsException(position);
}
if (_collection[position] == null)
{
_collection[position] = obj;
@ -133,4 +143,14 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
if (_collection?.Length > 0)
{
Array.Sort(_collection, comparer);
Array.Reverse(_collection);
}
}
}

View File

@ -14,13 +14,13 @@ public class StorageCollection<T>
/// <summary>
/// Словарь (хранилище) с коллекциями
/// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
/// <summary>
/// Возвращение списка названий коллекций
/// </summary>
public List<string> Keys => _storages.Keys.ToList();
public List<CollectionInfo> Keys => _storages.Keys.ToList();
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
@ -43,7 +43,7 @@ public class StorageCollection<T>
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
@ -53,7 +53,8 @@ public class StorageCollection<T>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
{
if (name == null || _storages.ContainsKey(name))
CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
if (collectionInfo.Name == null || _storages.ContainsKey(collectionInfo))
{
return;
}
@ -64,10 +65,10 @@ public class StorageCollection<T>
case CollectionType.None:
return;
case CollectionType.List:
_storages.Add(name, new ListGenericObjects<T> { });
_storages.Add(collectionInfo, new ListGenericObjects<T> { });
return;
case CollectionType.Massive:
_storages.Add(name, new MassiveGenericObjects<T> { });
_storages.Add(collectionInfo, new MassiveGenericObjects<T> { });
return;
}
}
@ -79,8 +80,12 @@ public class StorageCollection<T>
/// <param name="name">Название коллекции</param>
public void DelCollection(string name)
{
if (name == null || !_storages.ContainsKey(name)) { return; }
_storages.Remove(name);
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (collectionInfo.Name == null || _storages.ContainsKey(collectionInfo))
{
return;
}
_storages.Remove(collectionInfo);
}
/// <summary>
@ -93,8 +98,9 @@ public class StorageCollection<T>
{
get
{
if (name == null || !_storages.ContainsKey(name)) { return null; }
return _storages[name];
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, "");
if (collectionInfo == null || !_storages.ContainsKey(collectionInfo)) { return null; }
return _storages[collectionInfo];
}
}
@ -121,17 +127,16 @@ public class StorageCollection<T>
using (StreamWriter fs = new StreamWriter(filename))
{
fs.WriteLine(_collectionKey.ToString());
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> kvpair in _storages)
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> kvpair in _storages)
{
// не сохраняем пустые коллекции
if (kvpair.Value.Count == 0)
continue;
sb.Append(kvpair.Key);
sb.Append(_separatorForKeyValue);
sb.Append(kvpair.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(kvpair.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in kvpair.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
@ -166,24 +171,24 @@ public class StorageCollection<T>
throw new ArgumentException("В файле нет данных");
if (str != _collectionKey.ToString())
throw new InvalidDataException("В файле неверные данные");
_storages.Clear();
while ((str = sr.ReadLine()) != null)
{
string[] record = str.Split(_separatorForKeyValue);
if (record.Length != 4)
if (record.Length != 3)
{
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
throw new InvalidOperationException("Не удалось создать коллекцию");
}
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
throw new Exception("Не удалось определить информацию коллекции:" + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
throw new Exception("Не удалось определить тип коллекции:" + record[1]);
collection.MaxCount = Convert.ToInt32(record[1]);
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningTrackedVehicle() is T trackedVehicle)
@ -199,7 +204,7 @@ public class StorageCollection<T>
}
}
}
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
}
}
}

View File

@ -0,0 +1,34 @@
namespace ProjectExcavator.Drawnings;
/// <summary>
/// Сравнение по цвету, скорости, весу
/// </summary>
public class DrawningTrackedVehicleCompareByColor : IComparer<DrawningTrackedVehicle?>
{
public int Compare(DrawningTrackedVehicle? x, DrawningTrackedVehicle? y)
{
if (x == null && y == null)
{
return 0;
}
if (x == null || x.EntityTrackedVehicle == null)
{
return -1;
}
if (y == null || y.EntityTrackedVehicle == null)
{
return 1;
}
if(x.EntityTrackedVehicle.BodyColor.Name != y.EntityTrackedVehicle.BodyColor.Name)
{
return x.EntityTrackedVehicle.BodyColor.Name.CompareTo(y.EntityTrackedVehicle.BodyColor.Name);
}
var speedCompare = x.EntityTrackedVehicle.Speed.CompareTo(y.EntityTrackedVehicle.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityTrackedVehicle.Weight.CompareTo(y.EntityTrackedVehicle.Weight);
}
}

View File

@ -0,0 +1,37 @@
namespace ProjectExcavator.Drawnings;
/// <summary>
/// Сравнение по типу, скорости, весу
/// </summary>
public class DrawningTrackedVehicleCompareByType : IComparer<DrawningTrackedVehicle?>
{
public int Compare(DrawningTrackedVehicle? x, DrawningTrackedVehicle? y)
{
if (x == null && y == null)
{
return 0;
}
if (x == null || x.EntityTrackedVehicle == null)
{
return -1;
}
if (y == null || y.EntityTrackedVehicle == null)
{
return 1;
}
if (!x.GetType().Name.Equals(y.GetType().Name))
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityTrackedVehicle.Speed.CompareTo(y.EntityTrackedVehicle.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityTrackedVehicle.Weight.CompareTo(y.EntityTrackedVehicle.Weight);
}
}

View File

@ -0,0 +1,67 @@
using ProjectExcavator.Entities;
using System.Diagnostics.CodeAnalysis;
namespace ProjectExcavator.Drawnings;
/// <summary>
/// Реализация сравнения двух объектов класса-прорисовки
/// </summary>
public class DrawningTrackedVehicleEqutables : IEqualityComparer<DrawningTrackedVehicle?>
{
public bool Equals(DrawningTrackedVehicle? x, DrawningTrackedVehicle? y)
{
if (x == null || x.EntityTrackedVehicle == null)
{
return false;
}
if (y == null || y.EntityTrackedVehicle == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityTrackedVehicle.Speed != y.EntityTrackedVehicle.Speed)
{
return false;
}
if (x.EntityTrackedVehicle.Weight != y.EntityTrackedVehicle.Weight)
{
return false;
}
if (x.EntityTrackedVehicle.BodyColor != y.EntityTrackedVehicle.BodyColor)
{
return false;
}
if (x is DrawningExcavator && y is DrawningExcavator)
{
EntityExcavator entityX = (EntityExcavator)x.EntityTrackedVehicle;
EntityExcavator entityY = (EntityExcavator)y.EntityTrackedVehicle;
if(entityX.Bucket != entityY.Bucket)
{
return false;
}
if(entityX.Supports != entityY.Supports)
{
return false;
}
if(entityX.AdditionalColor != entityY.AdditionalColor)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningTrackedVehicle obj)
{
return obj.GetHashCode();
}
}

View File

@ -1,5 +1,5 @@
using ProjectExcavator.Drawnings;
using ProjectExcavator.Entities;
using ProjectExcavator.Entities;
namespace ProjectExcavator.Drawnings;
/// <summary>
/// Расширение для класса TrackedVehicle

View File

@ -0,0 +1,20 @@
using System.Runtime.Serialization;
namespace ProjectExcavator.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[Serializable]
internal class ObjectExistsException : ApplicationException
{
public ObjectExistsException(int count) : base("Вставка существуюзего объекта") { }
public ObjectExistsException() : base() { }
public ObjectExistsException(string message) : base(message) { }
public ObjectExistsException(string message, Exception exception) : base(message, exception) { }
protected ObjectExistsException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -52,6 +52,8 @@
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
buttonSortByType = new Button();
buttonSortByColor = new Button();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
@ -75,6 +77,8 @@
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddTrackedVehicle);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
@ -100,9 +104,9 @@
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top;
buttonRefresh.Location = new Point(3, 240);
buttonRefresh.Location = new Point(1, 174);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(215, 40);
buttonRefresh.Size = new Size(215, 30);
buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
@ -111,7 +115,7 @@
// maskedTextBoxPosition
//
maskedTextBoxPosition.Anchor = AnchorStyles.Top;
maskedTextBoxPosition.Location = new Point(3, 115);
maskedTextBoxPosition.Location = new Point(4, 59);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(215, 27);
@ -121,9 +125,9 @@
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top;
buttonGoToCheck.Location = new Point(3, 194);
buttonGoToCheck.Location = new Point(4, 138);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(215, 40);
buttonGoToCheck.Size = new Size(214, 30);
buttonGoToCheck.TabIndex = 5;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
@ -132,7 +136,7 @@
// ButtonRemoveExcavator
//
ButtonRemoveExcavator.Anchor = AnchorStyles.Top;
ButtonRemoveExcavator.Location = new Point(3, 148);
ButtonRemoveExcavator.Location = new Point(3, 92);
ButtonRemoveExcavator.Name = "ButtonRemoveExcavator";
ButtonRemoveExcavator.Size = new Size(215, 40);
ButtonRemoveExcavator.TabIndex = 4;
@ -306,6 +310,26 @@
openFileDialog.FileName = "openFileDialog1";
openFileDialog.Filter = "txt file | *.txt";
//
// buttonSortByType
//
buttonSortByType.Location = new Point(1, 210);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(215, 27);
buttonSortByType.TabIndex = 8;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += ButtonSortByType_Click;
//
// buttonSortByColor
//
buttonSortByColor.Location = new Point(3, 243);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(213, 27);
buttonSortByColor.TabIndex = 9;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += ButtonSortByColor_Click;
//
// FormExcavatorCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
@ -355,5 +379,7 @@
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@ -82,12 +82,16 @@ public partial class FormExcavatorCollection : Form
_logger.LogInformation("Добавлен объект: " + trackedVehicle.GetDataForSave());
}
}
//catch (ObjectNotFoundException) { }
catch (CollectionOverflowException ex)
{
MessageBox.Show("В коллекции превышено допустимое количество элементов:");
_logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
}
catch (ObjectExistsException ex)
{
MessageBox.Show("Такой объект есть в коллекции");
_logger.LogWarning($"Добавление существующего объекта: {ex.Message}");
}
}
/// <summary>
@ -256,7 +260,7 @@ public partial class FormExcavatorCollection : Form
for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{
string? colName = _storageCollection.Keys?[i];
string? colName = _storageCollection.Keys?[i].Name;
if (!string.IsNullOrEmpty(colName))
{
listBoxCollection.Items.Add(colName);
@ -342,4 +346,39 @@ public partial class FormExcavatorCollection : Form
}
}
}
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByColor_Click(object sender, EventArgs e)
{
CompareCars(new DrawningTrackedVehicleCompareByColor());
}
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByType_Click(object sender, EventArgs e)
{
CompareCars(new DrawningTrackedVehicleCompareByType());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void CompareCars(IComparer<DrawningTrackedVehicle?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}