PIbd-11 Levchenko G.A. LabWork08 Base #8

Closed
Geo7312 wants to merge 2 commits from LabWork08 into LabWork07
13 changed files with 396 additions and 50 deletions

View File

@ -57,7 +57,7 @@ public abstract class AbstractCompany
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningTrolleyB trolleyB)
{
return company._collection.Insert(trolleyB);
return company._collection.Insert(trolleyB, new DrawningTrolleyBEqutables());
}
/// <summary>
@ -97,6 +97,12 @@ public abstract class AbstractCompany
return bitmap;
}
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравниватель объектов</param>
public void Sort(IComparer<DrawningTrolleyB?> comparer) => _collection?.CollectionSort(comparer);
protected abstract void DrawBackground(Graphics g);
protected abstract void SetObjectPosition();

View File

@ -0,0 +1,72 @@
namespace ProjectTrolleybus.CollectionGenericObjects;
/// <summary>
/// Класс, хранящий информацию по коллекции
/// </summary>
public class 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;
}
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

@ -1,4 +1,5 @@
namespace ProjectTrolleybus.CollectionGenericObjects;
using ProjectTrolleybus.Drawnings;
namespace ProjectTrolleybus.CollectionGenericObjects;
/// <summary>
/// Интерфейс описания действий для набора хранимых объектов
@ -22,14 +23,14 @@ public interface ICollectionGenericObjects<T>
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
int Insert(T obj);
int Insert(T obj, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Добавление объекта в коллекцию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, int position);
int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
@ -56,4 +57,10 @@ public interface ICollectionGenericObjects<T>
/// <returns>Поэлементный вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Сравниватель объектов</param>
void CollectionSort(IComparer<T?> comparer);
}

View File

@ -1,5 +1,7 @@
namespace ProjectTrolleybus.CollectionGenericObjects;
using ProjectTrolleybus.Exceptions;
using ProjectTrolleybus.Exceptions;
using ProjectTrolleybus.Drawnings;
namespace ProjectTrolleybus.CollectionGenericObjects;
/// <summary>
/// Параметризированный набор объектов
@ -42,8 +44,13 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
// TODO выброс ошибки, если такой объект есть в коллекции
if (comparer != null && _collection.Contains(obj, comparer))
{
throw new CollectionAlreadyExistsException();
}
// проверка, что не превышено максимальное количество элементов
if (_collection.Count >= _maxCount)
{
@ -55,8 +62,14 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
// TODO выброс ошибки, если такой объект есть в коллекции
if (comparer != null && _collection.Contains(obj, comparer))
{
throw new CollectionAlreadyExistsException();
}
// проверка, что не превышено максимальное количество элементов
if (Count >= _maxCount)
throw new CollectionOverflowException(_maxCount);
@ -89,4 +102,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 @@
namespace ProjectTrolleybus.CollectionGenericObjects;
using ProjectTrolleybus.Drawnings;
using ProjectTrolleybus.Exceptions;
/// <summary>
@ -61,8 +62,13 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
// TODO выброс ошибки, если такой объект есть в коллекции
if (comparer != null && _collection.Contains(obj, comparer))
{
throw new CollectionAlreadyExistsException();
}
// вставка в свободное место набора
int index = 0;
while (index < _collection.Length)
@ -78,8 +84,13 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
// TODO выброс ошибки, если такой объект есть в коллекции
if (comparer != null && _collection.Contains(obj, comparer))
{
throw new CollectionAlreadyExistsException();
}
// проверка позиции
if (position >= _collection.Length || position < 0)
throw new PositionOutOfCollectionException(position);
@ -143,4 +154,14 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
}
public void CollectionSort(IComparer<T?> comparer)
{
List<T?> lst = [.. _collection];
lst.Sort(comparer.Compare);
for (int i = 0; i < _collection.Length; ++i)
{
_collection[i] = lst[i];
}
}
}

View File

@ -13,12 +13,12 @@ public class StorageCollection<T>
/// <summary>
/// Словарь (хранилище) с коллекциями
/// </summary>
private 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>
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
@ -50,17 +50,22 @@ public class StorageCollection<T>
/// <param name="collectionType">тип коллецкии</param>
public void AddCollection(string name, CollectionType collectionType)
{
if (!(collectionType == CollectionType.None) && !_storages.ContainsKey(name))
// проверка, что name не пустой и нет в словаре записи с таким ключом
if (string.IsNullOrEmpty(name) || _storages.ContainsKey(new CollectionInfo(name, collectionType, string.Empty)))
{
if (collectionType == CollectionType.List)
{
_storages.Add(name, new ListGenericObjects<T>());
}
else if (collectionType == CollectionType.Massive)
{
_storages.Add(name, new MassiveGenericObjects<T>());
}
MessageBox.Show("Коллекция с таким именем уже существует", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
// прописать логику для добавления
if (collectionType == CollectionType.List)
{
_storages.Add(new CollectionInfo(name, collectionType, string.Empty), new ListGenericObjects<T>());
}
if (collectionType == CollectionType.Massive)
{
_storages.Add(new CollectionInfo(name, collectionType, string.Empty), new MassiveGenericObjects<T>());
}
}
/// <summary>
@ -69,7 +74,8 @@ public class StorageCollection<T>
/// <param name="name">Название коллекции</param>
public void DelCollection(string name)
{
if (_storages.ContainsKey(name)) { _storages.Remove(name); }
if (!_storages.ContainsKey(new CollectionInfo(name, CollectionType.None, string.Empty))) return;
_storages.Remove(new CollectionInfo(name, CollectionType.None, string.Empty));
}
/// <summary>
/// Доступ к коллекции
@ -80,9 +86,9 @@ public class StorageCollection<T>
{
get
{
if (_storages.ContainsKey(name))
if (_storages.ContainsKey(new CollectionInfo(name, CollectionType.None, string.Empty)))
{
return _storages[name];
return _storages[new CollectionInfo(name, CollectionType.None, string.Empty)];
}
return null;
}
@ -108,7 +114,7 @@ public class StorageCollection<T>
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)
{
writer.Write(Environment.NewLine);
// не сохраняем пустые коллекции
@ -119,8 +125,6 @@ public class StorageCollection<T>
writer.Write(value.Key);
writer.Write(_separatorForKeyValue);
writer.Write(value.Value.GetCollectionType);
writer.Write(_separatorForKeyValue);
writer.Write(value.Value.MaxCount);
writer.Write(_separatorForKeyValue);
@ -171,21 +175,18 @@ public class StorageCollection<T>
while ((strs = reader.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);
if (collection == null)
{
throw new Exception("Не удалось создать коллекцию");
}
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?.CreateDrawningTrolleyB() is T trolleyB)
@ -204,7 +205,7 @@ public class StorageCollection<T>
}
}
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
}
}
}

View File

@ -0,0 +1,36 @@
using ProjectTrolleybus.Entities;
namespace ProjectTrolleybus.Drawnings;
/// <summary>
/// Сравнение по цвету, скорости, весу
/// </summary>
public class DrawningTrolleyBCompareByColor : IComparer<DrawningTrolleyB?>
{
public int Compare(DrawningTrolleyB? x, DrawningTrolleyB? y)
{
// TODO прописать логику сравнения по цветам, скорости, весу
if (x == null || x.EntityTrolleyB == null)
{
return 1;
}
if (y == null || y.EntityTrolleyB == null)
{
return -1;
}
if (x.EntityTrolleyB.BodyColor != y.EntityTrolleyB.BodyColor)
{
return x.EntityTrolleyB.BodyColor.Name.CompareTo(y.EntityTrolleyB.BodyColor.Name);
}
var speedCompare = x.EntityTrolleyB.Speed.CompareTo(y.EntityTrolleyB.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityTrolleyB.Weight.CompareTo(y.EntityTrolleyB.Weight);
}
}

View File

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

View File

@ -0,0 +1,71 @@
using System.Diagnostics.CodeAnalysis;
using ProjectTrolleybus.Entities;
namespace ProjectTrolleybus.Drawnings;
/// <summary>
/// Реализация сравнения двух объектов класса-прорисовки
/// </summary>
public class DrawningTrolleyBEqutables : IEqualityComparer<DrawningTrolleyB?>
{
public bool Equals(DrawningTrolleyB? x, DrawningTrolleyB? y)
{
if (x == null || x.EntityTrolleyB == null)
{
return false;
}
if (y == null || y.EntityTrolleyB == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityTrolleyB.Speed != y.EntityTrolleyB.Speed)
{
return false;
}
if (x.EntityTrolleyB.Weight != y.EntityTrolleyB.Weight)
{
return false;
}
if (x.EntityTrolleyB.BodyColor != y.EntityTrolleyB.BodyColor)
{
return false;
}
if (x is DrawningTrolleybus && y is DrawningTrolleybus)
{
// TODO доделать логику сравнения дополнительных параметров
EntityTrolleybus xTrolleybus = (EntityTrolleybus)x.EntityTrolleyB;
EntityTrolleybus yTrolleybus = (EntityTrolleybus)y.EntityTrolleyB;
if (xTrolleybus.AdditionalColor != yTrolleybus.AdditionalColor)
{
return false;
}
if (xTrolleybus.BatteryCompartment != yTrolleybus.BatteryCompartment)
{
return false;
}
if (xTrolleybus.Horns != yTrolleybus.Horns)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningTrolleyB obj)
{
return obj.GetHashCode();
}
}

View File

@ -0,0 +1,13 @@
using ProjectTrolleybus.CollectionGenericObjects;
using System.Runtime.Serialization;
namespace ProjectTrolleybus.Exceptions;
internal class CollectionAlreadyExistsException : ApplicationException
{
public CollectionAlreadyExistsException(CollectionInfo collectionInfo) : base("В коллекции уже есть такой элемент: " + collectionInfo) { }
public CollectionAlreadyExistsException() : base("В коллекции уже есть такой элемент") { }
public CollectionAlreadyExistsException(string message) : base(message) { }
public CollectionAlreadyExistsException(string message, Exception exception) : base(message, exception) { }
protected CollectionAlreadyExistsException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}

View File

@ -2,6 +2,9 @@
namespace ProjectTrolleybus.Exceptions;
/// <summary>
/// Класс, описывающий ошибку, что позиция вышла за границы коллекции
/// </summary>
[Serializable]
internal class PositionOutOfCollectionException : ApplicationException
{

View File

@ -52,6 +52,8 @@
LoadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
buttonSortByColor = new Button();
buttonSortByType = new Button();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
@ -68,13 +70,15 @@
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(875, 24);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(201, 636);
groupBoxTools.Size = new Size(201, 678);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddTrolleyB);
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
panelCompanyTools.Controls.Add(buttonRefresh);
@ -82,15 +86,15 @@
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 355);
panelCompanyTools.Location = new Point(3, 361);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(195, 278);
panelCompanyTools.Size = new Size(195, 314);
panelCompanyTools.TabIndex = 8;
//
// buttonAddTrolleyB
//
buttonAddTrolleyB.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddTrolleyB.Location = new Point(3, 12);
buttonAddTrolleyB.Location = new Point(3, 3);
buttonAddTrolleyB.Name = "buttonAddTrolleyB";
buttonAddTrolleyB.Size = new Size(189, 41);
buttonAddTrolleyB.TabIndex = 1;
@ -101,7 +105,7 @@
// maskedTextBoxPosition
//
maskedTextBoxPosition.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
maskedTextBoxPosition.Location = new Point(3, 106);
maskedTextBoxPosition.Location = new Point(3, 50);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(189, 23);
@ -111,7 +115,7 @@
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(3, 229);
buttonRefresh.Location = new Point(3, 176);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(189, 41);
buttonRefresh.TabIndex = 6;
@ -122,7 +126,7 @@
// buttonRemoveTrolleyB
//
buttonRemoveTrolleyB.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveTrolleyB.Location = new Point(3, 135);
buttonRemoveTrolleyB.Location = new Point(3, 82);
buttonRemoveTrolleyB.Name = "buttonRemoveTrolleyB";
buttonRemoveTrolleyB.Size = new Size(189, 41);
buttonRemoveTrolleyB.TabIndex = 4;
@ -133,7 +137,7 @@
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(3, 182);
buttonGoToCheck.Location = new Point(3, 129);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(189, 41);
buttonGoToCheck.TabIndex = 5;
@ -250,7 +254,7 @@
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(875, 636);
pictureBox.Size = new Size(875, 678);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
@ -295,11 +299,33 @@
openFileDialog.FileName = "openFileDialog1";
openFileDialog.Filter = "txt file | *.txt";
//
// buttonSortByColor
//
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByColor.Location = new Point(3, 270);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(189, 41);
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(3, 223);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(189, 41);
buttonSortByType.TabIndex = 7;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += ButtonSortByType_Click;
//
// FormTrolleyBCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1076, 660);
ClientSize = new Size(1076, 702);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
@ -344,5 +370,7 @@
private ToolStripMenuItem LoadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@ -81,6 +81,11 @@ public partial class FormTrolleyBCollection : Form
MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (CollectionAlreadyExistsException ex)
{
MessageBox.Show(ex.Message);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@ -269,7 +274,7 @@ public partial class FormTrolleyBCollection : 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);
@ -323,4 +328,35 @@ public partial class FormTrolleyBCollection : Form
}
}
}
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByType_Click(object sender, EventArgs e)
{
CompareTrolleyBuses(new DrawningTrolleyBCompareByType());
}
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByColor_Click(object sender, EventArgs e)
{
CompareTrolleyBuses(new DrawningTrolleyBCompareByColor());
}
private void CompareTrolleyBuses(IComparer<DrawningTrolleyB?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}