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

This commit is contained in:
qkrlnt 2024-05-18 16:26:55 +04:00
parent 5d47765f02
commit d5e19301a4
13 changed files with 346 additions and 43 deletions

View File

@ -70,7 +70,7 @@ public abstract class AbstractCompany
{
return -1;
}
return company._collection.Insert(train);
return company._collection.Insert(train, new DrawingTrainEqutables());
}
/// <summary>
@ -117,6 +117,13 @@ public abstract class AbstractCompany
return bitmap;
}
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawingTrain?> comparer) => _collection?.CollectionSort(comparer);
/// <summary>
/// Вывод заднего фона
/// </summary>

View File

@ -0,0 +1,77 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectMonorail.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;
}
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 @@
using ProjectMonorail.CollectionGenericObjects;
using ProjectMonorail.Drawings;
using System;
using System.Collections.Generic;
using System.Linq;
@ -28,16 +29,18 @@ public interface ICollectionGenericObjects<T>
/// Добавление объекта в коллекцию
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <param name="comparer">Cравнение двух объектов</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">Cравнение двух объектов</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, int position);
int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
@ -63,4 +66,10 @@ public interface ICollectionGenericObjects<T>
/// </summary>
/// <returns>Поэлементный вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
/// <summary>
/// Сортировка коллекции
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
void CollectionSort(IComparer<T?> comparer);
}

View File

@ -1,5 +1,7 @@
using ProjectMonorail.CollectionGenericObject;
using ProjectMonorail.Drawings;
using ProjectMonorail.Exceptions;
using System.Linq;
namespace ProjectMonorail.CollectionGenericObjects;
@ -40,17 +42,19 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
if (Count + 1 > _maxCount) { throw new CollectionOverflowException(); }
if (_collection.Contains(obj, comparer)) { throw new ObjectExistsException(); }
_collection.Add(obj);
return Count + 1;
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (Count + 1 > _maxCount) { throw new CollectionOverflowException(); }
if (position < 0 || position >= Count) { throw new PositionOutOfCollectionException(); }
if (_collection.Contains(obj, comparer)) { throw new ObjectExistsException(); }
_collection.Insert(position, obj);
return Count + 1;
}
@ -70,4 +74,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 ProjectMonorail.CollectionGenericObjects;
using ProjectMonorail.Drawings;
using ProjectMonorail.Exceptions;
namespace ProjectMonorail.CollectionGenericObject;
@ -56,8 +57,9 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
if (_collection.Contains(obj, comparer)) { throw new ObjectExistsException(); }
for (int i = 0; i < Count; i++)
{
if (_collection[i] == null)
@ -69,9 +71,10 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
throw new CollectionOverflowException();
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (position < 0 || position >= Count) { throw new PositionOutOfCollectionException(); }
if (_collection.Contains(obj, comparer)) { throw new ObjectExistsException(); }
for (int i = position; i < Count; i++)
{
if (_collection[i] == null)
@ -107,4 +110,9 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
}

View File

@ -1,6 +1,7 @@
using ProjectMonorail.CollectionGenericObject;
using ProjectMonorail.Drawings;
using ProjectMonorail.Exceptions;
using System.Collections;
namespace ProjectMonorail.CollectionGenericObjects;
@ -14,12 +15,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>
/// Ключевое слово, с которого должен начинаться файл
@ -41,7 +42,7 @@ public class StorageCollection<T>
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
@ -51,16 +52,17 @@ public class StorageCollection<T>
/// <param name="collectionType">Тип коллекции</param>
public void AddCollection(String name, CollectionType collectionType)
{
if (name == null || _storages.ContainsKey(name)) { return; }
switch (collectionType)
CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
if (collectionInfo.Name == null || _storages.ContainsKey(collectionInfo)) { return; }
switch (collectionInfo.CollectionType)
{
case CollectionType.None:
break;
case CollectionType.Massive:
_storages.Add(name, new MassiveGenericObjects<T>());
_storages.Add(collectionInfo, new MassiveGenericObjects<T>());
break;
case CollectionType.List:
_storages.Add(name, new ListGenericObjects<T>());
_storages.Add(collectionInfo, new ListGenericObjects<T>());
break;
}
}
@ -71,21 +73,23 @@ 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>
/// Доступ к коллекции
/// </summary>
/// <param name="name">Название коллекции</param>
/// <returns></returns>
public ICollectionGenericObjects<T>? this[String name]
public ICollectionGenericObjects<T>? this[String collectionName]
{
get
{
if (_storages.TryGetValue(name, out ICollectionGenericObjects<T>? value)) { return value; }
return null;
CollectionInfo collectionInfo = new CollectionInfo(collectionName, CollectionType.None, "");
if (collectionInfo == null || !_storages.ContainsKey(collectionInfo)) { return null; }
return _storages[collectionInfo];
}
}
@ -108,7 +112,7 @@ public class StorageCollection<T>
using FileStream fs = new(filename, FileMode.Create);
using StreamWriter streamWriter = new StreamWriter(fs);
streamWriter.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
streamWriter.Write(Environment.NewLine);
@ -120,8 +124,6 @@ public class StorageCollection<T>
streamWriter.Write(value.Key);
streamWriter.Write(_separatorForKeyValue);
streamWriter.Write(value.Value.GetCollectionType);
streamWriter.Write(_separatorForKeyValue);
streamWriter.Write(value.Value.MaxCount);
streamWriter.Write(_separatorForKeyValue);
@ -166,20 +168,18 @@ public class StorageCollection<T>
while (!streamReader.EndOfStream)
{
string[] record = streamReader.ReadLine().Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
if (record.Length != 4)
if (record.Length != 3)
{
continue;
}
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
throw new InvalidCastException("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[2]);
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]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawingTrain() is T train)
@ -197,8 +197,7 @@ public class StorageCollection<T>
}
}
}
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
}
}

View File

@ -0,0 +1,29 @@
namespace ProjectMonorail.Drawings;
/// <summary>
/// Сравнение по цвету, скорости, весу
/// </summary>
public class DrawingTrainCompareByColor : IComparer<DrawingTrain?>
{
public int Compare(DrawingTrain? x, DrawingTrain? y)
{
if (x == null || x.EntityTrain == null)
{
return -1;
}
if (y == null || y.EntityTrain == null)
{
return 1;
}
if (x.EntityTrain.MainColor.Name != y.EntityTrain.MainColor.Name)
{
return x.EntityTrain.MainColor.Name.CompareTo(y.EntityTrain.MainColor.Name);
}
var speedCompare = x.EntityTrain.Speed.CompareTo(y.EntityTrain.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityTrain.Weight.CompareTo(y.EntityTrain.Weight);
}
}

View File

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

View File

@ -0,0 +1,65 @@
using ProjectMonorail.Entities;
using System.Diagnostics.CodeAnalysis;
namespace ProjectMonorail.Drawings;
/// <summary>
/// Реализация сравнения двух объектов класса-прорисовки
/// </summary>
public class DrawingTrainEqutables : IEqualityComparer<DrawingTrain?>
{
public bool Equals(DrawingTrain? x, DrawingTrain? y)
{
if (x == null || x.EntityTrain == null)
{
return false;
}
if (y == null || y.EntityTrain == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityTrain.Speed != y.EntityTrain.Speed)
{
return false;
}
if (x.EntityTrain.Weight != y.EntityTrain.Weight)
{
return false;
}
if (x.EntityTrain.MainColor != y.EntityTrain.MainColor)
{
return false;
}
if (x is DrawingMonorail && y is DrawingMonorail)
{
EntityMonorail newX = (EntityMonorail)x.EntityTrain;
EntityMonorail newY = (EntityMonorail)y.EntityTrain;
if (newX.AdditionalColor != newY.AdditionalColor)
{
return false;
}
if (newX.Wheels != newY.Wheels)
{
return false;
}
if (newX.Rail != newY.Rail)
{
return false;
}
if (newX.SecondСarriage != newY.SecondСarriage)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawingTrain? obj)
{
return obj.GetHashCode();
}
}

View File

@ -0,0 +1,18 @@
using System.Runtime.Serialization;
namespace ProjectMonorail.Exceptions;
/// <summary>
/// Класс, описывающий ошибку добавления уже существующего объекта
/// </summary>
[Serializable]
public class ObjectExistsException : ApplicationException
{
public ObjectExistsException() : base("Данный объект уже существует") { }
public ObjectExistsException(string message) : base(message) { }
public ObjectExistsException(string message, Exception exception) : base(message, exception) { }
protected ObjectExistsException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}

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();
@ -70,13 +72,15 @@
groupBoxTools.Margin = new Padding(3, 2, 3, 2);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Padding = new Padding(3, 2, 3, 2);
groupBoxTools.Size = new Size(200, 592);
groupBoxTools.Size = new Size(200, 642);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Controls.Add(buttonRemoveTrain);
@ -84,9 +88,9 @@
panelCompanyTools.Controls.Add(buttonAddTrain);
panelCompanyTools.Dock = DockStyle.Bottom;
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 383);
panelCompanyTools.Location = new Point(3, 370);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(194, 207);
panelCompanyTools.Size = new Size(194, 270);
panelCompanyTools.TabIndex = 8;
//
// buttonRefresh
@ -150,7 +154,7 @@
// buttonCreateCompany
//
buttonCreateCompany.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonCreateCompany.Location = new Point(6, 344);
buttonCreateCompany.Location = new Point(6, 332);
buttonCreateCompany.Margin = new Padding(3, 2, 3, 2);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(185, 34);
@ -247,7 +251,7 @@
comboBoxSelectorCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectorCompany.FormattingEnabled = true;
comboBoxSelectorCompany.Items.AddRange(new object[] { "Хранилище" });
comboBoxSelectorCompany.Location = new Point(6, 317);
comboBoxSelectorCompany.Location = new Point(6, 305);
comboBoxSelectorCompany.Margin = new Padding(3, 2, 3, 2);
comboBoxSelectorCompany.Name = "comboBoxSelectorCompany";
comboBoxSelectorCompany.Size = new Size(185, 23);
@ -260,7 +264,7 @@
pictureBox.Location = new Point(0, 24);
pictureBox.Margin = new Padding(3, 2, 3, 2);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(1006, 592);
pictureBox.Size = new Size(1006, 642);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
@ -305,11 +309,35 @@
openFileDialog.FileName = "openFileDialog1";
openFileDialog.Filter = "txt file | *.txt";
//
// buttonSortByColor
//
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByColor.Location = new Point(3, 229);
buttonSortByColor.Margin = new Padding(3, 2, 3, 2);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(185, 34);
buttonSortByColor.TabIndex = 14;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += ButtonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByType.Location = new Point(3, 191);
buttonSortByType.Margin = new Padding(3, 2, 3, 2);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(185, 34);
buttonSortByType.TabIndex = 13;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += ButtonSortByType_Click;
//
// FormTrainCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1206, 616);
ClientSize = new Size(1206, 666);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
@ -355,5 +383,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 FormTrainCollection : Form
MessageBox.Show("Коллекция переполнена");
_logger.LogWarning($"Не удалось добавить объект в коллекцию: {ex.Message}");
}
catch (ObjectExistsException ex)
{
MessageBox.Show("Данный объект уже существует");
_logger.LogWarning($"Не удалось добавить объект в коллекцию: {ex.Message}");
}
}
/// <summary>
@ -245,7 +250,7 @@ public partial class FormTrainCollection : 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);
@ -333,4 +338,22 @@ public partial class FormTrainCollection : Form
}
}
}
private void ButtonSortByType_Click(object sender, EventArgs e)
{
CompareTrains(new DrawingTrainCompareByType());
}
private void ButtonSortByColor_Click(object sender, EventArgs e)
{
CompareTrains(new DrawingTrainCompareByColor());
}
private void CompareTrains(IComparer<DrawingTrain?> comparer)
{
if (_company == null) { return; }
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}

View File

@ -127,6 +127,6 @@
<value>261, 17</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>44</value>
<value>48</value>
</metadata>
</root>