PIbd-13 Gutorov I. A. LabWork08 Simple #8

Closed
vasmaae wants to merge 1 commits from LabWork08 into LabWork07
12 changed files with 326 additions and 39 deletions

View File

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

View File

@ -0,0 +1,76 @@
namespace ProjectAirbus.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

@ -20,16 +20,18 @@ public interface ICollectionGenericObjects<T> where T : class
/// Добавление объекта в коллекцию
/// </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>
/// Удаление объекта из коллекции с конкретной позиции
@ -55,4 +57,10 @@ public interface ICollectionGenericObjects<T> where T : class
/// </summary>
/// <returns>Поэлементный вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
}

View File

@ -52,8 +52,15 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T> where T : clas
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectNotUniqueException();
}
}
if (Count == _maxCount)
{
throw new CollectionOverflowException(Count);
@ -62,8 +69,15 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T> where T : clas
return Count;
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectNotUniqueException();
}
}
if (Count == _maxCount)
{
throw new CollectionOverflowException(Count);
@ -94,4 +108,9 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T> where T : clas
yield return _collection[i];
}
}
void ICollectionGenericObjects<T>.CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}

View File

@ -1,4 +1,6 @@
using ProjectAirbus.Exceptions;
using ProjectAirbus.Drawnings;
using ProjectAirbus.Exceptions;
using System.Collections.Immutable;
namespace ProjectAirbus.CollectionGenericObjects;
@ -57,8 +59,18 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T> where T : c
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
if (comparer != null)
{
foreach (T? item in _collection)
{
if ((comparer as IEqualityComparer<DrawningAirbus>).Equals(obj as DrawningAirbus, item as DrawningAirbus))
{
throw new ObjectNotUniqueException();
}
}
}
// TODO вставка в свободное место набора
for (int i = 0; i < Count; i++)
{
@ -72,7 +84,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T> where T : c
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
// TODO проверка позиции
// TODO проверка, что элемент массима по этой позиции пустой,
@ -140,4 +152,9 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T> where T : c
yield return _collection[i];
}
}
void ICollectionGenericObjects<T>.CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
}

View File

@ -13,12 +13,12 @@ public class StorageCollection<T> where T : DrawningAirbus
/// <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>
/// Ключевое слово, с которого должен начинаться файл
@ -40,7 +40,7 @@ public class StorageCollection<T> where T : DrawningAirbus
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
@ -50,18 +50,20 @@ public class StorageCollection<T> where T : DrawningAirbus
/// <param name="collectionType">Тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
{
if (_storages.ContainsKey(name) || collectionType == CollectionType.None)
CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
if (_storages.ContainsKey(collectionInfo) || collectionInfo.CollectionType == CollectionType.None)
{
return;
}
switch (collectionType)
switch (collectionInfo.CollectionType)
{
case CollectionType.Massive:
_storages[name] = new MassiveGenericObjects<T>();
_storages[collectionInfo] = new MassiveGenericObjects<T>();
break;
case CollectionType.List:
_storages[name] = new ListGenericObjects<T>();
_storages[collectionInfo] = new ListGenericObjects<T>();
break;
}
}
@ -72,9 +74,10 @@ public class StorageCollection<T> where T : DrawningAirbus
/// <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) && collectionInfo != null)
{
_storages.Remove(name);
_storages.Remove(collectionInfo);
}
}
@ -87,10 +90,11 @@ public class StorageCollection<T> where T : DrawningAirbus
{
get
{
if (_storages.ContainsKey(name))
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo))
{
return _storages[name];
}
return _storages[collectionInfo];
}
return null;
}
}
@ -114,7 +118,7 @@ public class StorageCollection<T> where T : DrawningAirbus
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
StringBuilder sb = new();
@ -127,8 +131,6 @@ public class StorageCollection<T> where T : DrawningAirbus
sb.Append(value.Key);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.MaxCount);
sb.Append(_separatorForKeyValue);
@ -179,17 +181,18 @@ public class StorageCollection<T> where T : DrawningAirbus
while ((strs = fs.ReadLine()) != null)
{
string[] record = strs.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?.CreateDrawningAirbus() is T airbus)
@ -207,7 +210,7 @@ public class StorageCollection<T> where T : DrawningAirbus
}
}
}
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
}
}
}

View File

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

View File

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

View File

@ -0,0 +1,43 @@
using ProjectAirbus.Entities;
using System.Diagnostics.CodeAnalysis;
namespace ProjectAirbus.Drawnings;
/// <summary>
/// Реализация сравнения двух объектов класса-прорисовки
/// </summary>
public class DrawningAirbusEqutables : IEqualityComparer<DrawningAirbus?>
{
public bool Equals(DrawningAirbus? x, DrawningAirbus? y)
{
if (x == null || x.EntityAirbus == null) return false;
if (y == null || y.EntityAirbus == null) return false;
if (x.GetType().Name != y.GetType().Name) return false;
if (x.EntityAirbus.Speed != y.EntityAirbus.Speed) return false;
if (x.EntityAirbus.Weight != y.EntityAirbus.Weight) return false;
if (x.EntityAirbus.BodyColor != y.EntityAirbus.BodyColor) return false;
if (x is DrawningBigAirbus bigX && y is DrawningBigAirbus bigY)
{
// TODO доделать логику сравнения дополнительных параметров
EntityBigAirbus _x = (EntityBigAirbus)x.EntityAirbus;
EntityBigAirbus _y = (EntityBigAirbus)y.EntityAirbus;
if (_x.AdditionalEngine != _y.AdditionalEngine) return false;
if (_x.PassengerCompartment != _y.PassengerCompartment) return false;
if (_x.AdditionalColor != _y.AdditionalColor) return false;
}
return true;
}
public int GetHashCode([DisallowNull] DrawningAirbus obj)
{
return obj.GetHashCode();
}
}

View File

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

View File

@ -52,6 +52,8 @@
LoadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
buttonSortByType = new Button();
buttonSortByColor = new Button();
groupBocTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
@ -68,13 +70,15 @@
groupBocTools.Dock = DockStyle.Right;
groupBocTools.Location = new Point(867, 24);
groupBocTools.Name = "groupBocTools";
groupBocTools.Size = new Size(172, 538);
groupBocTools.Size = new Size(172, 552);
groupBocTools.TabIndex = 0;
groupBocTools.TabStop = false;
groupBocTools.Text = "Инструменты";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonAddAirbus);
panelCompanyTools.Controls.Add(buttonRemoveAirbus);
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
@ -82,9 +86,9 @@
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 337);
panelCompanyTools.Location = new Point(3, 338);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(166, 198);
panelCompanyTools.Size = new Size(166, 211);
panelCompanyTools.TabIndex = 10;
//
// buttonAddAirbus
@ -100,7 +104,7 @@
//
// buttonRemoveAirbus
//
buttonRemoveAirbus.Location = new Point(3, 114);
buttonRemoveAirbus.Location = new Point(3, 61);
buttonRemoveAirbus.Name = "buttonRemoveAirbus";
buttonRemoveAirbus.Size = new Size(160, 23);
buttonRemoveAirbus.TabIndex = 4;
@ -111,7 +115,7 @@
// maskedTextBoxPosition
//
maskedTextBoxPosition.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
maskedTextBoxPosition.Location = new Point(3, 85);
maskedTextBoxPosition.Location = new Point(3, 32);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(160, 23);
@ -120,7 +124,7 @@
//
// buttonGoToCheck
//
buttonGoToCheck.Location = new Point(3, 143);
buttonGoToCheck.Location = new Point(3, 90);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(160, 23);
buttonGoToCheck.TabIndex = 5;
@ -130,7 +134,7 @@
//
// buttonRefresh
//
buttonRefresh.Location = new Point(3, 172);
buttonRefresh.Location = new Point(3, 119);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(160, 23);
buttonRefresh.TabIndex = 6;
@ -249,7 +253,7 @@
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(867, 538);
pictureBox.Size = new Size(867, 552);
pictureBox.TabIndex = 7;
pictureBox.TabStop = false;
//
@ -293,10 +297,30 @@
//
openFileDialog.Filter = "txt file | *.txt";
//
// buttonSortByType
//
buttonSortByType.Location = new Point(3, 148);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(160, 23);
buttonSortByType.TabIndex = 8;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// buttonSortByColor
//
buttonSortByColor.Location = new Point(3, 177);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(160, 23);
buttonSortByColor.TabIndex = 9;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += buttonSortByColor_Click;
//
// FormAirbusCollection
//
AutoScaleMode = AutoScaleMode.None;
ClientSize = new Size(1039, 562);
ClientSize = new Size(1039, 576);
Controls.Add(pictureBox);
Controls.Add(groupBocTools);
Controls.Add(menuStrip);
@ -341,5 +365,7 @@
private ToolStripMenuItem LoadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonSortByType;
private Button buttonSortByColor;
}
}

View File

@ -85,6 +85,11 @@ public partial class FormAirbusCollection : Form
MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (ObjectNotUniqueException ex)
{
MessageBox.Show("Такой объект уже присутствует в коллекции");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
/// <summary>
@ -250,7 +255,7 @@ public partial class FormAirbusCollection : 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);
@ -335,4 +340,25 @@ public partial class FormAirbusCollection : Form
}
RefreshListBoxItems();
}
private void buttonSortByType_Click(object sender, EventArgs e)
{
CompareCars(new DrawningAirbusCompareByType());
}
private void buttonSortByColor_Click(object sender, EventArgs e)
{
CompareCars(new DrawningAirbusCompareByColor());
}
private void CompareCars(IComparer<DrawningAirbus?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}