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

This commit is contained in:
VladaM 2024-02-24 17:57:43 +04:00
parent 522a85b337
commit f3f35d54bf
11 changed files with 370 additions and 41 deletions

View File

@ -76,7 +76,7 @@ public abstract class AbstractCompany
/// <returns></returns>
public static bool operator +(AbstractCompany company, DrawningTanker tanker)
{
return company._collection?.Insert(tanker) ?? false;
return company._collection?.Insert(tanker, new DrawningTankerEqutables()) ?? false;
}
/// <summary>
@ -100,6 +100,12 @@ public abstract class AbstractCompany
return _collection?.Get(rnd.Next(GetMaxCount));
}
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningTanker?> comparer) => _collection?.CollectionSort(comparer);
/// <summary>
/// Вывод всей коллекции
/// </summary>

View File

@ -0,0 +1,76 @@
namespace GasolineTanker.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">Cравнение двух объектов</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
bool Insert(T obj);
bool Insert(T obj, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Добавление объекта в коллекцию на конкретную позицию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param>
/// <param name="comparer">Cравнение двух объектов</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
bool Insert(T obj, int position);
bool 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

@ -54,18 +54,25 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position];
}
public bool Insert(T obj)
public bool Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
if (Count == _maxCount)
{
throw new CollectionOverflowException(Count);
}
if (_collection.Contains(obj, comparer))
{
throw new Exception("Такой объект уже существует в коллекции");
}
_collection.Add(obj);
return true;
}
public bool Insert(T obj, int position)
public bool Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (Count == _maxCount)
{
throw new CollectionOverflowException(Count);
@ -74,6 +81,10 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
{
throw new PositionOutOfCollectionException(position);
}
if (_collection.Contains(obj, comparer))
{
throw new Exception("Такой объект уже существует в коллекции");
}
_collection.Insert(position, obj);
return true;
}
@ -84,6 +95,10 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
{
throw new PositionOutOfCollectionException(position);
}
if (_collection[position] == null)
{
throw new ObjectNotFoundException(position);
}
_collection.RemoveAt(position);
return true;
@ -96,4 +111,12 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
if (_collection != null && _collection.Count > 0)
{
_collection.Sort(comparer);
}
}
}

View File

@ -61,8 +61,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
/// Вставка в пустое место
/// </summary>
public bool Insert(T obj)
public bool Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
if (_collection.Contains(obj, comparer))
{
throw new Exception("Такой объект уже существует в коллекции");
}
for (int i = 0; i < _collection.Length; ++i)
{
if (_collection[i] == null)
@ -78,8 +82,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
/// Вставка по позиции
/// </summary>
public bool Insert(T obj, int position)
public bool Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (_collection.Contains(obj, comparer))
{
throw new Exception("Такой объект уже существует в коллекции");
}
if (position < 0 || position >= Count)
{
throw new PositionOutOfCollectionException(position);
@ -133,4 +141,14 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
;
if (_collection != null && _collection.Length > 0)
{
Array.Sort(_collection, comparer);
_collection = _collection.OrderBy(element => element == null).ToArray();
}
}
}

View File

@ -14,12 +14,12 @@ public class StorageCollection<T>
/// <summary>
/// Словарь (хранилище) с коллекциями
/// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
/// <summary>
/// Возвращение списка названий коллекций
/// </summary>
public List<string> Keys => _storages.Keys.ToList();
public List<CollectionInfo> Keys => _storages.Keys.ToList();
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
@ -42,7 +42,7 @@ public class StorageCollection<T>
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
@ -52,17 +52,19 @@ public class StorageCollection<T>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
{
if (_storages.ContainsKey(name) || name == null)
CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
if (_storages.ContainsKey(collectionInfo) || name == null)
{
throw new Exception("Неверное имя коллекции");
}
if (collectionType == CollectionType.Massive)
{
_storages.Add(name, new MassiveGenericObjects<T>());
_storages.Add(collectionInfo, new MassiveGenericObjects<T>());
}
if (collectionType == CollectionType.List)
{
_storages.Add(name, new ListGenericObjects<T>());
_storages.Add(collectionInfo, new ListGenericObjects<T>());
}
}
@ -72,9 +74,10 @@ public class StorageCollection<T>
/// <param name="name">Название коллекции</param>
public void DelCollection(string name)
{
if (_storages.ContainsKey(name) && name != null)
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo) && name != null)
{
_storages.Remove(name);
_storages.Remove(collectionInfo);
}
}
@ -87,9 +90,10 @@ public class StorageCollection<T>
{
get
{
if (_storages.ContainsKey(name) && name != null)
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo) && name != null)
{
return _storages[name];
return _storages[collectionInfo];
}
return null;
}
@ -114,7 +118,7 @@ public class StorageCollection<T>
StringBuilder sb = new();
sb.Append(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
sb.Append(Environment.NewLine);
// не сохраняем пустые коллекции
@ -125,8 +129,6 @@ public class StorageCollection<T>
sb.Append(value.Key);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.MaxCount);
sb.Append(_separatorForKeyValue);
@ -185,18 +187,19 @@ public class StorageCollection<T>
foreach (string data in strs)
{
string[] record = data.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
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) ??
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[2]);
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningTanker() is T tanker)
@ -205,7 +208,7 @@ public class StorageCollection<T>
{
if (!collection.Insert(tanker))
{
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
throw new Exception("Объект не удалось добавить в коллекцию: " + record[2]);
}
}
catch (CollectionOverflowException ex)
@ -215,7 +218,7 @@ public class StorageCollection<T>
}
}
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
}
}

View File

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

View File

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

View File

@ -0,0 +1,68 @@
using GasolineTanker.Entities;
using System.Diagnostics.CodeAnalysis;
namespace GasolineTanker.Drawnings;
/// <summary>
/// Реализация сравнения двух объектов класса-прорисовки
/// </summary>
public class DrawningTankerEqutables : IEqualityComparer<DrawningTanker?>
{
public bool Equals(DrawningTanker? x, DrawningTanker? y)
{
if (x == null || x.EntityTanker == null)
{
return false;
}
if (y == null || y.EntityTanker == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityTanker.Speed != y.EntityTanker.Speed)
{
return false;
}
if (x.EntityTanker.Weight != y.EntityTanker.Weight)
{
return false;
}
if (x.EntityTanker.BodyColor != y.EntityTanker.BodyColor)
{
return false;
}
if (x is DrawningGasolineTanker && y is DrawningGasolineTanker)
{
EntityGasolineTanker entityGasolineTankerX = (EntityGasolineTanker)x.EntityTanker;
EntityGasolineTanker entityGasolineTankerY = (EntityGasolineTanker)y.EntityTanker;
if (entityGasolineTankerX.AdditionalColor != entityGasolineTankerY.AdditionalColor)
{
return false;
}
if (entityGasolineTankerX.SignalBeacon != entityGasolineTankerY.SignalBeacon)
{
return false;
}
if (entityGasolineTankerX.Cistern != entityGasolineTankerY.Cistern)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningTanker obj)
{
return obj.GetHashCode();
}
}

View File

@ -30,6 +30,8 @@
{
groupBoxTools = new GroupBox();
panelCompanyTools = new Panel();
buttonSortByColor = new Button();
buttonSortByType = new Button();
buttonAddTanker = new Button();
maskedTextBoxPosition = new MaskedTextBox();
buttonRefresh = new Button();
@ -68,13 +70,15 @@
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(874, 24);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(179, 531);
groupBoxTools.Size = new Size(179, 615);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddTanker);
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
panelCompanyTools.Controls.Add(buttonRefresh);
@ -83,9 +87,31 @@
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(14, 331);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(159, 196);
panelCompanyTools.Size = new Size(159, 284);
panelCompanyTools.TabIndex = 9;
//
// buttonSortByColor
//
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByColor.Location = new Point(10, 239);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(143, 33);
buttonSortByColor.TabIndex = 8;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += buttonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByType.Location = new Point(10, 203);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(143, 33);
buttonSortByType.TabIndex = 7;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// buttonAddTanker
//
buttonAddTanker.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
@ -109,7 +135,7 @@
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(8, 147);
buttonRefresh.Location = new Point(8, 164);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(143, 33);
buttonRefresh.TabIndex = 6;
@ -133,7 +159,7 @@
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(10, 110);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(141, 31);
buttonGoToCheck.Size = new Size(141, 48);
buttonGoToCheck.TabIndex = 5;
buttonGoToCheck.Text = "Отправить на проверку";
buttonGoToCheck.UseVisualStyleBackColor = true;
@ -247,7 +273,7 @@
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(874, 531);
pictureBox.Size = new Size(874, 615);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
@ -293,7 +319,7 @@
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1053, 555);
ClientSize = new Size(1053, 639);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
@ -338,5 +364,7 @@
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@ -225,13 +225,12 @@ public partial class FormTankerCollection : Form
listBoxCollection.Items.Clear();
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);
}
}
}
/// <summary>
@ -313,4 +312,41 @@ public partial class FormTankerCollection : Form
}
RerfreshListBoxItems();
}
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSortByType_Click(object sender, EventArgs e)
{
CompareTankers(new DrawningTankerCompareByType());
}
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void buttonSortByColor_Click(object sender, EventArgs e)
{
CompareTankers(new DrawningTankerCompareByColor());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void CompareTankers(IComparer<DrawningTanker?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}