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

This commit is contained in:
Kirill 2024-09-14 20:57:30 +04:00
parent 54925fa133
commit 84a0b0bcb6
12 changed files with 365 additions and 64 deletions

View File

@ -61,7 +61,7 @@ public abstract class AbstractCompany
/// <returns></returns>
public static int? operator +(AbstractCompany company, DrawningTrain train)
{
return company._collection?.Insert(train);
return company._collection?.Insert(train, new DrawningTrainEqutables());
}
/// <summary>
@ -119,4 +119,6 @@ public abstract class AbstractCompany
/// Расстановка объектов
/// </summary>
protected abstract void SetObjectsPosition();
public void Sort(IComparer<DrawningTrain?> comparer) => _collection?.CollectionSort(comparer);
}

View File

@ -0,0 +1,58 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRoadTrain.CollectionGenericObjects;
public class CollectionInfo
{
public string Name { get; private set; }
public CollectionType CollectionType { get; private set; }
public string Description { get; private set; }
private static readonly string _separator = "-";
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

@ -22,7 +22,7 @@ where T : class
/// </summary>
/// <param name="obj">Добавляемый объект</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj);
int Insert(T obj, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Добавление объекта в коллекцию на конкретную позицию
@ -30,7 +30,7 @@ where T : class
/// <param name="obj">Добавляемый объект</param>
/// <param name="position">Позиция</param>
/// <returns>true - вставка прошла удачно, false - вставка не удалась</returns>
int Insert(T obj, int position);
int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
/// <summary>
/// Удаление объекта из коллекции с конкретной позиции
@ -57,4 +57,6 @@ where T : class
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
void CollectionSort(IComparer<T?> comparer);
}

View File

@ -59,8 +59,15 @@ where T : class
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 ObjectIsEqualException();
}
}
// TODO проверка, что не превышено максимальное количество элементов
// TODO вставка в конец набора
if (Count == _maxCount) throw new CollectionOverflowException(Count);
@ -68,8 +75,15 @@ where T : class
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 ObjectIsEqualException();
}
}
// TODO проверка, что не превышено максимальное количество элементов
// TODO проверка позиции
// TODO вставка по позиции
@ -96,4 +110,9 @@ where T : class
yield return _collection[i];
}
}
void ICollectionGenericObjects<T>.CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}

View File

@ -1,4 +1,5 @@

using ProjectRoadTrain.Drawnings;
using ProjectRoadTrain.Exceptions;
namespace ProjectRoadTrain.CollectionGenericObjects;
@ -55,8 +56,16 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
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<DrawningTrain>).Equals(obj as DrawningTrain, item as DrawningTrain))
throw new ObjectIsEqualException();
}
}
// TODO вставка в свободное место набора
int index = 0;
while (index < _collection.Length)
@ -72,8 +81,16 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
throw new CollectionOverflowException(Count);
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (comparer != null)
{
foreach (T? item in _collection)
{
if ((comparer as IEqualityComparer<DrawningTrain>).Equals(obj as DrawningTrain, item as DrawningTrain))
throw new ObjectIsEqualException();
}
}
// TODO проверка позиции
// TODO проверка, что элемент массива по этой позиции пустой, если нет, то
// ищется свободное место после этой позиции и идет вставка туда
@ -129,4 +146,9 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
void ICollectionGenericObjects<T>.CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
}

View File

@ -18,11 +18,11 @@ where T : DrawningTrain
/// <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>
/// Ключевое слово, с которого должен начинаться файл
@ -44,7 +44,7 @@ where T : DrawningTrain
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
/// Добавление коллекции в хранилище
@ -53,12 +53,13 @@ where T : DrawningTrain
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
{
if (_storages.ContainsKey(name)) return;
CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
if (_storages.ContainsKey(collectionInfo)) return;
if (collectionType == CollectionType.None) return;
else if (collectionType == CollectionType.Massive)
_storages[name] = new MassiveGenericObjects<T>();
_storages[collectionInfo] = new MassiveGenericObjects<T>();
else if (collectionType == CollectionType.List)
_storages[name] = new ListGenericObjects<T>();
_storages[collectionInfo] = new ListGenericObjects<T>();
}
/// <summary>
@ -68,7 +69,9 @@ where T : DrawningTrain
public void DelCollection(string name)
{
// TODO Прописать логику для удаления коллекции
if (_storages.ContainsKey(name)) { _storages.Remove(name); }
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo))
_storages.Remove(collectionInfo);
}
/// <summary>
/// Доступ к коллекции
@ -79,9 +82,9 @@ where T : DrawningTrain
{
get
{
// TODO Продумать логику получения объекта
if (_storages.ContainsKey(name))
return _storages[name];
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo))
return _storages[collectionInfo];
return null;
}
}
@ -96,34 +99,26 @@ where T : DrawningTrain
{
throw new Exception("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
File.Delete(filename);
}
using FileStream fs = new(filename, FileMode.Create);
using StreamWriter streamWriter = new StreamWriter(fs);
streamWriter.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
using (StreamWriter writer = new StreamWriter(filename))
{
streamWriter.Write(Environment.NewLine);
writer.Write(_collectionKey);
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
StringBuilder sb = new();
sb.Append(Environment.NewLine);
// не сохраняем пустые коллекции
if (value.Value.Count == 0)
{
continue;
}
streamWriter.Write(value.Key);
streamWriter.Write(_separatorForKeyValue);
streamWriter.Write(value.Value.GetCollectionType);
streamWriter.Write(_separatorForKeyValue);
streamWriter.Write(value.Value.MaxCount);
streamWriter.Write(_separatorForKeyValue);
sb.Append(value.Key);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
@ -131,12 +126,12 @@ where T : DrawningTrain
{
continue;
}
streamWriter.Write(data);
streamWriter.Write(_separatorItems);
sb.Append(data);
sb.Append(_separatorItems);
}
writer.Write(sb);
}
}
}
/// <summary>
@ -154,18 +149,24 @@ where T : DrawningTrain
{
string? str;
str = sr.ReadLine();
if (str == null || str.Length == 0)
{
throw new Exception("В файле нет данных");
}
if (str != _collectionKey.ToString())
throw new FormatException("В файле неверные данные");
_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);
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
throw new Exception("Не удалось определить информацию коллекции: " + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
throw new Exception("Не удалось создать коллекцию");
if (collection == null)
{
throw new InvalidOperationException("Не удалось определить тип коллекции:" + record[1]);
@ -191,7 +192,7 @@ where T : DrawningTrain
}
}
}
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
}
}
}

View File

@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRoadTrain.Drawnings;
public class DrawningTrainCompareByColor : IComparer<DrawningTrain?>
{
public int Compare(DrawningTrain? x, DrawningTrain? y)
{
if (x == null || x.EntityTrain == null)
{
return 1;
}
if (y == null || y.EntityTrain == null)
{
return -1;
}
var bodycolorCompare = x.EntityTrain.BodyColor.Name.CompareTo(y.EntityTrain.BodyColor.Name);
if (bodycolorCompare != 0)
{
return bodycolorCompare;
}
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,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRoadTrain.Drawnings;
public class DrawningTrainCompareByType : IComparer<DrawningTrain?>
{
public int Compare(DrawningTrain? x, DrawningTrain? 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,62 @@
using ProjectRoadTrain.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRoadTrain.Drawnings;
public class DrawningTrainEqutables : IEqualityComparer<DrawningTrain?>
{
public bool Equals(DrawningTrain? x, DrawningTrain? 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.BodyColor != y.EntityTrain.BodyColor)
{
return false;
}
if (x is DrawningRoadTrain && y is DrawningRoadTrain)
{
EntityRoadTrain _x = (EntityRoadTrain)x.EntityTrain;
EntityRoadTrain _y = (EntityRoadTrain)x.EntityTrain;
if (_x.AdditionalColor != _y.AdditionalColor)
{
return false;
}
if (_x.Tank != _y.Tank)
{
return false;
}
if (_x.Fetlock != _y.Fetlock)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningTrain obj)
{
return obj.GetHashCode();
}
}

View File

@ -0,0 +1,18 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectRoadTrain.Exceptions;
[Serializable]
public class ObjectIsEqualException : ApplicationException
{
public ObjectIsEqualException(int count) : base("В коллекции содержится равный элемент: " + count) { }
public ObjectIsEqualException() : base() { }
public ObjectIsEqualException(string message) : base(message) { }
public ObjectIsEqualException(string message, Exception exception) : base(message, exception) { }
protected ObjectIsEqualException(SerializationInfo info, StreamingContext contex) : base(info, contex) { }
}

View File

@ -30,6 +30,8 @@
{
groupBoxTools = new GroupBox();
panelCompanyTools = new Panel();
buttonSortByType = new Button();
buttonSortByColor = new Button();
buttonAddTrain = new Button();
buttonRemoveTrain = new Button();
maskedTextBox = new MaskedTextBox();
@ -67,7 +69,7 @@
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(732, 24);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(290, 565);
groupBoxTools.Size = new Size(290, 612);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Tag = "";
@ -75,6 +77,8 @@
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonAddTrain);
panelCompanyTools.Controls.Add(buttonRemoveTrain);
panelCompanyTools.Controls.Add(maskedTextBox);
@ -84,13 +88,35 @@
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 361);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(284, 201);
panelCompanyTools.Size = new Size(284, 248);
panelCompanyTools.TabIndex = 8;
//
// buttonSortByType
//
buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByType.Location = new Point(3, 177);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(272, 29);
buttonSortByType.TabIndex = 7;
buttonSortByType.Text = "Сортировать по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// buttonSortByColor
//
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByColor.Location = new Point(3, 212);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(272, 31);
buttonSortByColor.TabIndex = 8;
buttonSortByColor.Text = "Соритровать по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += buttonSortByColor_Click;
//
// buttonAddTrain
//
buttonAddTrain.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonAddTrain.Location = new Point(3, 21);
buttonAddTrain.Location = new Point(3, 3);
buttonAddTrain.Name = "buttonAddTrain";
buttonAddTrain.Size = new Size(272, 30);
buttonAddTrain.TabIndex = 1;
@ -101,7 +127,7 @@
// buttonRemoveTrain
//
buttonRemoveTrain.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveTrain.Location = new Point(3, 97);
buttonRemoveTrain.Location = new Point(3, 68);
buttonRemoveTrain.Name = "buttonRemoveTrain";
buttonRemoveTrain.Size = new Size(272, 31);
buttonRemoveTrain.TabIndex = 3;
@ -111,17 +137,17 @@
//
// maskedTextBox
//
maskedTextBox.Location = new Point(17, 68);
maskedTextBox.Location = new Point(3, 39);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(240, 23);
maskedTextBox.Size = new Size(272, 23);
maskedTextBox.TabIndex = 6;
maskedTextBox.ValidatingType = typeof(int);
//
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(3, 134);
buttonGoToCheck.Location = new Point(3, 105);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(272, 29);
buttonGoToCheck.TabIndex = 4;
@ -132,7 +158,7 @@
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(3, 167);
buttonRefresh.Location = new Point(3, 140);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(272, 31);
buttonRefresh.TabIndex = 5;
@ -251,7 +277,7 @@
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(732, 565);
pictureBox.Size = new Size(732, 612);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
@ -300,7 +326,7 @@
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1022, 589);
ClientSize = new Size(1022, 636);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
@ -345,5 +371,7 @@
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonSortByType;
private Button buttonSortByColor;
}
}

View File

@ -237,7 +237,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);
@ -267,7 +267,7 @@ public partial class FormTrainCollection : Form
switch (comboBoxSelectorCompany.Text)
{
case "Хранилище":
_company = new TrainSharingService (pictureBox.Width, pictureBox.Height, collection);
_company = new TrainSharingService(pictureBox.Width, pictureBox.Height, collection);
break;
}
panelCompanyTools.Enabled = true;
@ -310,4 +310,24 @@ public partial class FormTrainCollection : Form
}
}
}
private void buttonSortByType_Click(object sender, EventArgs e)
{
CompareTrain(new DrawningTrainCompareByType());
}
private void buttonSortByColor_Click(object sender, EventArgs e)
{
CompareTrain(new DrawningTrainCompareByColor());
}
private void CompareTrain(IComparer<DrawningTrain?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}