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

This commit is contained in:
SVETLANA_8 2024-06-13 21:04:28 +04:00
parent b116e7870c
commit 81b6990ac8
12 changed files with 351 additions and 59 deletions

View File

@ -63,7 +63,7 @@ public abstract class AbstractCompany
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningTrackedCar trackedCar)
{
return company._collection.Insert(trackedCar);
return company._collection.Insert(trackedCar, new DrawiningTrackedCarEqutables());
}
/// <summary>
/// Перегрузка оператора удаления для класса
@ -122,4 +122,8 @@ public abstract class AbstractCompany
/// Расстановка объектов
/// </summary>
protected abstract void SetObjectsPosition();
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningTrackedCar?> comparer) => _collection?.CollectionSort(comparer);
}

View File

@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectByldozer.CollectionGenericObjects;
public class CollectionInfo : IEquatable<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

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

View File

@ -51,18 +51,29 @@ public class ListGenericObjects<T>: ICollectionGenericObjects<T>
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
// TODO выброс ошибки если переполнение
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectIsEqualException();
}
}
if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
// TODO выброс ошибки если переполнение
// TODO выброс ошибки если за границу
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectIsEqualException();
}
}
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj);
@ -88,5 +99,10 @@ public class ListGenericObjects<T>: ICollectionGenericObjects<T>
yield return _collection[i];
}
}
void ICollectionGenericObjects<T>.CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}

View File

@ -1,4 +1,5 @@
using ProjectByldozer.Exceptions;
using ProjectByldozer.Drawnings;
using ProjectByldozer.Exceptions;
namespace ProjectByldozer.CollectionGenericObjects;
/// <summary>
@ -56,9 +57,16 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
// TODO выброс ошибки если переполнение
if (comparer != null)
{
foreach (T? item in _collection)
{
if ((comparer as IEqualityComparer<DrawningTrackedCar>).Equals(obj as DrawningTrackedCar, item as DrawningTrackedCar))
throw new ObjectIsEqualException();
}
}
int index = 0;
while (index < _collection.Length)
{
@ -72,10 +80,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)
{
// TODO выброс ошибки если переполнение
// TODO выброс ошибки если выход за границу
if (comparer != null)
{
foreach (T? item in _collection)
{
if ((comparer as IEqualityComparer<DrawningTrackedCar>).Equals(obj as DrawningTrackedCar, item as DrawningTrackedCar))
throw new ObjectIsEqualException();
}
}
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null)
{
@ -123,4 +137,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
void ICollectionGenericObjects<T>.CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
}

View File

@ -15,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>
/// Ключевое слово, с которого должен начинаться файл
/// </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,16 +50,13 @@ public class StorageCollection<T>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
{
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом
// TODO Прописать логику для добавления
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,9 +65,9 @@ public class StorageCollection<T>
/// <param name="name">Название коллекции</param>
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>
@ -82,9 +79,9 @@ public class StorageCollection<T>
{
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;
}
}
@ -113,7 +110,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);
if (value.Value.Count == 0)
@ -122,8 +119,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);
foreach (T? item in value.Value.GetItems())
@ -171,27 +166,28 @@ public class StorageCollection<T>
string strs = "";
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("Не удалось создать коллекцию");
if (collection == null)
{
throw new Exception("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningTrackedCar() is T TrackedCar)
if (elem?.CreateDrawningTrackedCar() is T ship)
{
try
{
if (collection.Insert(TrackedCar) == -1)
if (collection.Insert(ship) == -1)
{
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
}
@ -202,7 +198,7 @@ public class StorageCollection<T>
}
}
}
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
}
}
}
@ -216,14 +212,14 @@ public class StorageCollection<T>
/// <param name="collectionType"></param>
/// <returns></returns>
private static ICollectionGenericObjects<T>? CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
return collectionType switch
{
CollectionType.Massive => new MassiveGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
CollectionType.Massive => new MassiveGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
}

View File

@ -0,0 +1,66 @@
using ProjectByldozer.Entities;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectByldozer.Drawnings;
public class DrawiningTrackedCarEqutables : IEqualityComparer<DrawningTrackedCar?>
{
public bool Equals(DrawningTrackedCar? x, DrawningTrackedCar? y)
{
if (x == null || x.EntityTrackedCar == null)
{
return false;
}
if (y == null || y.EntityTrackedCar == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityTrackedCar.Speed != y.EntityTrackedCar.Speed)
{
return false;
}
if (x.EntityTrackedCar.Weight != y.EntityTrackedCar.Weight)
{
return false;
}
if (x.EntityTrackedCar.BodyColor != y.EntityTrackedCar.BodyColor)
{
return false;
}
if (x is DrawningByldozer && y is DrawningByldozer)
{
EntityByldozer _x = (EntityByldozer)x.EntityTrackedCar;
EntityByldozer _y = (EntityByldozer)x.EntityTrackedCar;
if (_x.AdditionalColor != _y.AdditionalColor)
{
return false;
}
if (_x.Dump != _y.Dump)
{
return false;
}
if (_x.Bakingpowder != _y.Bakingpowder)
{
return false;
}
if (_x.Pipe != _y.Pipe)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningTrackedCar obj)
{
return obj.GetHashCode();
}
}

View File

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectByldozer.Drawnings
{
public class DrawningTrackedCarCompareByColor : IComparer<DrawningTrackedCar?>
{
public int Compare(DrawningTrackedCar? x, DrawningTrackedCar? y)
{
if (x == null || x.EntityTrackedCar == null)
{
return 1;
}
if (y == null || y.EntityTrackedCar == null)
{
return -1;
}
var bodycolorCompare = x.EntityTrackedCar.BodyColor.Name.CompareTo(y.EntityTrackedCar.BodyColor.Name);
if (bodycolorCompare != 0)
{
return bodycolorCompare;
}
var speedCompare = x.EntityTrackedCar.Speed.CompareTo(y.EntityTrackedCar.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityTrackedCar.Weight.CompareTo(y.EntityTrackedCar.Weight);
}
}
}

View File

@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectByldozer.Drawnings
{
public class DrawningTrackedCarCompareByType : IComparer<DrawningTrackedCar?>
{
public int Compare(DrawningTrackedCar? x, DrawningTrackedCar? y)
{
if (x == null || x.EntityTrackedCar == null)
{
return 1;
}
if (y == null || y.EntityTrackedCar == null)
{
return -1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityTrackedCar.Speed.CompareTo(y.EntityTrackedCar.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityTrackedCar.Weight.CompareTo(y.EntityTrackedCar.Weight);
}
}
}

View File

@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ProjectByldozer.Exceptions;
/// <summary>
/// Класс, описывающий ошибку переполнения коллекции
/// </summary>
[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

@ -52,6 +52,8 @@
loadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
buttonSortByColor = new Button();
buttonSortByType = new Button();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
@ -75,15 +77,17 @@
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonAddTrackedCar);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(buttonGoToCheck);
panelCompanyTools.Controls.Add(maskedTextBox);
panelCompanyTools.Controls.Add(buttonDelCar);
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 293);
panelCompanyTools.Location = new Point(3, 264);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(208, 176);
panelCompanyTools.Size = new Size(208, 230);
panelCompanyTools.TabIndex = 9;
//
// buttonAddTrackedCar
@ -145,7 +149,7 @@
comboBoxSelectionCompany.DropDownStyle = ComboBoxStyle.DropDownList;
comboBoxSelectionCompany.FormattingEnabled = true;
comboBoxSelectionCompany.Items.AddRange(new object[] { "Хранилище" });
comboBoxSelectionCompany.Location = new Point(3, 238);
comboBoxSelectionCompany.Location = new Point(5, 209);
comboBoxSelectionCompany.Name = "comboBoxSelectionCompany";
comboBoxSelectionCompany.Size = new Size(203, 23);
comboBoxSelectionCompany.TabIndex = 0;
@ -153,7 +157,7 @@
//
// buttonCreateCompany
//
buttonCreateCompany.Location = new Point(3, 267);
buttonCreateCompany.Location = new Point(5, 238);
buttonCreateCompany.Name = "buttonCreateCompany";
buttonCreateCompany.Size = new Size(203, 20);
buttonCreateCompany.TabIndex = 8;
@ -173,12 +177,12 @@
panelStorage.Dock = DockStyle.Top;
panelStorage.Location = new Point(3, 19);
panelStorage.Name = "panelStorage";
panelStorage.Size = new Size(203, 214);
panelStorage.Size = new Size(203, 184);
panelStorage.TabIndex = 7;
//
// buttonCollectionDel
//
buttonCollectionDel.Location = new Point(3, 182);
buttonCollectionDel.Location = new Point(2, 152);
buttonCollectionDel.Name = "buttonCollectionDel";
buttonCollectionDel.Size = new Size(191, 20);
buttonCollectionDel.TabIndex = 6;
@ -192,7 +196,7 @@
listBoxCollection.ItemHeight = 15;
listBoxCollection.Location = new Point(3, 112);
listBoxCollection.Name = "listBoxCollection";
listBoxCollection.Size = new Size(191, 64);
listBoxCollection.Size = new Size(191, 34);
listBoxCollection.TabIndex = 5;
//
// buttonCjllecyionAdd
@ -292,6 +296,27 @@
//
saveFileDialog.FileName = "txt file | *.txt";
//
// buttonSortByColor
//
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByColor.Location = new Point(2, 202);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(208, 25);
buttonSortByColor.TabIndex = 11;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += ButtonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Location = new Point(2, 175);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(203, 31);
buttonSortByType.TabIndex = 12;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += ButtonSortByType_Click;
//
// FormCarCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
@ -341,5 +366,7 @@
private ToolStripMenuItem loadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@ -73,9 +73,9 @@ public partial class FormCarCollection : Form
MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (PositionOutOfCollectionException ex)
catch (ObjectIsEqualException ex)
{
MessageBox.Show("Выход за границы коллекции");
MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@ -111,6 +111,7 @@ public partial class FormCarCollection : Form
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
private void ButtonGoToCheck_Click(object sender, EventArgs e)
@ -194,7 +195,7 @@ public partial class FormCarCollection : 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);
@ -296,4 +297,22 @@ public partial class FormCarCollection : Form
}
}
private void ButtonSortByType_Click(object sender, EventArgs e)
{
CompareTrackedaCar(new DrawningTrackedCarCompareByType());
}
private void ButtonSortByColor_Click(object sender, EventArgs e)
{
CompareTrackedaCar(new DrawningTrackedCarCompareByColor());
}
private void CompareTrackedaCar(IComparer<DrawningTrackedCar?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}