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

This commit is contained in:
Азамат Иштуганов 2024-05-19 22:20:51 +04:00
parent da56612369
commit e59d527bfc
12 changed files with 382 additions and 44 deletions

View File

@ -51,7 +51,7 @@ public abstract class AbstractCompany
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawningBoat boat)
{
return company._collection.Insert(boat);
return company._collection.Insert(boat, new DrawningBoatEqutables());
}
/// <summary>
/// Перегрузка оператора удаления для класса
@ -90,6 +90,9 @@ public abstract class AbstractCompany
}
return bitmap;
}
public void Sort(IComparer<DrawningBoat?> comparer) => _collection?.CollectionSort(comparer);
/// <summary>
/// Вывод заднего фона
/// </summary>

View File

@ -0,0 +1,78 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorBoat.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

@ -18,15 +18,17 @@ public interface ICollectionGenericObjects<T>
/// Добавление объекта в коллекцию
/// </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>
/// Удаление объекта из коллекции с конкретной позиции
/// </summary>
@ -50,4 +52,6 @@ public interface ICollectionGenericObjects<T>
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
void CollectionSort(IComparer<T?> comparer);
}

View File

@ -51,17 +51,31 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
if (_collection[position] == null) throw new ObjectNotFoundException();
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectAlreadyExistsException();
}
}
_collection.Add(obj);
return Count;
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
if (comparer != null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectAlreadyExistsException(position);
}
}
_collection.Insert(position, obj);
return position;
}
@ -80,4 +94,9 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
}

View File

@ -44,8 +44,18 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
if (position < 0 || position >= Count) throw new PositionOutOfCollectionException();
return _collection[position];
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
if (comparer != null)
{
foreach (T? i in _collection)
{
if (comparer.Equals(i, obj))
{
throw new ObjectAlreadyExistsException(i);
}
}
}
for (int i = 0; i < Count; i++)
{
if (_collection[i] == null)
@ -56,12 +66,22 @@ 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 (comparer != null)
{
foreach (T? i in _collection)
{
if (comparer.Equals(i, obj))
{
throw new ObjectAlreadyExistsException(i);
}
}
}
if (_collection[position] == null)
{
_collection[position] = obj;
@ -88,7 +108,7 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
--temp;
}
return -1;
throw new CollectionOverflowException();
}
public T? Remove(int position)
{
@ -106,4 +126,9 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
}

View File

@ -1,5 +1,6 @@
using MotorBoat.Drawnings;
using MotorBoat.Exceptions;
using System.Data;
namespace MotorBoat.CollectionGenericObjects;
@ -13,7 +14,7 @@ public class StorageCollection<T>
/// <summary>
/// Словарь (хранилище) с коллекциями
/// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages;
readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
@ -33,14 +34,14 @@ public class StorageCollection<T>
/// <summary>
/// Возвращение списка названий коллекций
/// </summary>
public List<string> Keys => _storages.Keys.ToList();
public List<CollectionInfo> Keys => _storages.Keys.ToList();
/// <summary>
/// Конструктор
/// </summary>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
/// Добавление коллекции в хранилище
@ -49,17 +50,18 @@ public class StorageCollection<T>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
{
if (name == null || _storages.ContainsKey(name))
CollectionInfo collectionInfo = new(name, collectionType, string.Empty);
if (name == null || _storages.ContainsKey(collectionInfo))
return;
switch (collectionType)
{
case CollectionType.None:
return;
case CollectionType.Massive:
_storages[name] = new MassiveGenericObjects<T>();
_storages[collectionInfo] = new MassiveGenericObjects<T>();
return;
case CollectionType.List:
_storages[name] = new ListGenericObjects<T>();
_storages[collectionInfo] = new ListGenericObjects<T>();
return;
default: break;
}
@ -71,8 +73,9 @@ public class StorageCollection<T>
/// <param name="name">Название коллекции</param>
public void DelCollection(string name)
{
if (_storages.ContainsKey(name))
_storages.Remove(name);
CollectionInfo collectionInfo = new(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo))
_storages.Remove(collectionInfo);
}
/// <summary>
@ -84,8 +87,9 @@ public class StorageCollection<T>
{
get
{
if (_storages.ContainsKey(name))
return _storages[name];
CollectionInfo collectionInfo = new(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo))
return _storages[collectionInfo];
return null;
}
}
@ -99,7 +103,7 @@ public class StorageCollection<T>
{
if (_storages.Count == 0)
{
throw new ArgumentException("В хранилище отсутствуют коллекции для сохранения");
throw new InvalidDataException("В хранилище отсутствуют коллекции для сохранения");
}
if (File.Exists(filename))
{
@ -108,7 +112,7 @@ public class StorageCollection<T>
using (StreamWriter writer = new(filename))
{
writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
writer.Write(Environment.NewLine);
// не сохраняем пустые коллекции
@ -118,8 +122,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);
@ -164,16 +166,20 @@ public class StorageCollection<T>
{
string[] record = line.Split(_separatorForKeyValue,
StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
if (record.Length != 3)
{
continue;
}
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
throw new Exception("Не удалось определить информацию коллекции" + record[0]);
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType) ??
throw new InvalidCastException("Не удалось определить тип коллекции:" + record[1]); ;
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems,
StringSplitOptions.RemoveEmptyEntries);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType);
if (collection == null)
{
throw new InvalidOperationException("Не удалось создать коллекцию");
}
collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningBoat() is T boat)
@ -182,16 +188,16 @@ public class StorageCollection<T>
{
if (collection.Insert(boat) == -1)
{
throw new InvalidOperationException("Объект не удалось добавить в коллекцию: " + record[3]);
throw new ConstraintException("Объект не удалось добавить в коллекцию: " + record[3]);
}
}
catch (CollectionOverflowException ex)
{
throw new CollectionOverflowException("Коллекция переполнена", ex);
throw new DataException("Коллекция переполнена", ex);
}
}
}
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
}
}
}

View File

@ -0,0 +1,38 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorBoat.Drawnings;
/// <summary>
/// Сравнение по цвету, скорости и весу
/// </summary>
public class DrawningBoatCompareByColor : IComparer<DrawningBoat?>
{
public int Compare(DrawningBoat? x, DrawningBoat? y)
{
if (x == null || x.EntityBoat == null)
{
return 1;
}
if (y == null || y.EntityBoat == null)
{
return -1;
}
var bodycolorCompare = x.EntityBoat.BodyColor.Name.CompareTo(y.EntityBoat.BodyColor.Name);
if (bodycolorCompare != 0)
{
return bodycolorCompare;
}
var speedCompare = x.EntityBoat.Speed.CompareTo(y.EntityBoat.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityBoat.Weight.CompareTo(y.EntityBoat.Weight);
}
}

View File

@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MotorBoat.Drawnings;
/// <summary>
/// Сравнение по типу, скорости и весу
/// </summary>
public class DrawningBoatCompareByType : IComparer<DrawningBoat?>
{
public int Compare(DrawningBoat? x, DrawningBoat? y)
{
if (x == null || x.EntityBoat == null)
{
return -1;
}
if (y == null || y.EntityBoat == null)
{
return 1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityBoat.Speed.CompareTo(y.EntityBoat.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityBoat.Weight.CompareTo(y.EntityBoat.Weight);
}
}

View File

@ -0,0 +1,58 @@
using MotorBoat.Entities;
using System.Diagnostics.CodeAnalysis;
namespace MotorBoat.Drawnings;
public class DrawningBoatEqutables : IEqualityComparer<DrawningBoat?>
{
public bool Equals(DrawningBoat? x, DrawningBoat? y)
{
if (x == null || x.EntityBoat == null)
{
return false;
}
if (y == null || y.EntityBoat == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityBoat.Speed != y.EntityBoat.Speed)
{
return false;
}
if (x.EntityBoat.Weight != y.EntityBoat.Weight)
{
return false;
}
if (x.EntityBoat.BodyColor != y.EntityBoat.BodyColor)
{
return false;
}
if (x is DrawningMotorBoat && y is DrawningMotorBoat)
{
EntityMotorBoat entityX = (EntityMotorBoat)x.EntityBoat;
EntityMotorBoat entityY = (EntityMotorBoat)y.EntityBoat;
if (entityX.Engine != entityY.Engine)
{
return false;
}
if (entityX.ProtectiveGlass != entityY.ProtectiveGlass)
{
return false;
}
if (entityX.AdditionalColor != entityY.AdditionalColor)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningBoat? obj)
{
return obj.GetHashCode();
}
}

View File

@ -0,0 +1,22 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace MotorBoat.Exceptions;
/// <summary>
/// Класс, описывающий ошибку, что в коллекции уже есть такой элемент
/// </summary>
[Serializable]
public class ObjectAlreadyExistsException : ApplicationException
{
public ObjectAlreadyExistsException(object i) : base("В коллекции уже есть такой элемент " + i) { }
public ObjectAlreadyExistsException() : base() { }
public ObjectAlreadyExistsException(string message) : base(message) { }
public ObjectAlreadyExistsException(string message, Exception exception) : base(message, exception)
{ }
protected ObjectAlreadyExistsException(SerializationInfo info, StreamingContext context) : base(info, context) { }
}

View File

@ -30,6 +30,8 @@
{
groupBoxTools = new GroupBox();
panelCompanyTools = new Panel();
buttonSortByColor = new Button();
buttonSortByType = new Button();
buttonAddBoat = new Button();
maskedTextBoxPosition = new MaskedTextBox();
buttonRefresh = new Button();
@ -68,13 +70,15 @@
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(630, 24);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(170, 512);
groupBoxTools.Size = new Size(170, 535);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddBoat);
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
panelCompanyTools.Controls.Add(buttonRefresh);
@ -83,9 +87,31 @@
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 316);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(164, 193);
panelCompanyTools.Size = new Size(164, 221);
panelCompanyTools.TabIndex = 8;
//
// buttonSortByColor
//
buttonSortByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByColor.Location = new Point(6, 190);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(158, 25);
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(6, 159);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(158, 25);
buttonSortByType.TabIndex = 7;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += ButtonSortByType_Click;
//
// buttonAddBoat
//
buttonAddBoat.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
@ -99,7 +125,7 @@
//
// maskedTextBoxPosition
//
maskedTextBoxPosition.Location = new Point(3, 70);
maskedTextBoxPosition.Location = new Point(3, 36);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(158, 23);
@ -109,7 +135,7 @@
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(3, 162);
buttonRefresh.Location = new Point(3, 128);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(158, 25);
buttonRefresh.TabIndex = 6;
@ -120,7 +146,7 @@
// buttonRemoveBoat
//
buttonRemoveBoat.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveBoat.Location = new Point(3, 99);
buttonRemoveBoat.Location = new Point(3, 65);
buttonRemoveBoat.Name = "buttonRemoveBoat";
buttonRemoveBoat.Size = new Size(158, 26);
buttonRemoveBoat.TabIndex = 4;
@ -131,7 +157,7 @@
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(3, 131);
buttonGoToCheck.Location = new Point(3, 97);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(158, 25);
buttonGoToCheck.TabIndex = 5;
@ -248,7 +274,7 @@
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(630, 512);
pictureBox.Size = new Size(630, 535);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
@ -297,7 +323,7 @@
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(800, 536);
ClientSize = new Size(800, 559);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
@ -342,5 +368,7 @@
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@ -77,6 +77,11 @@ public partial class FormBoatCollection : Form
MessageBox.Show("Не удалось добавить объект");
_logger.LogWarning($"Не удалось добавить объект: {ex.Message}");
}
catch (ObjectAlreadyExistsException)
{
MessageBox.Show("Такой объект уже существует");
_logger.LogError("Ошибка: такой объект уже существует {0}", boat);
}
}
/// <summary>
/// Удаление лодки
@ -199,10 +204,6 @@ public partial class FormBoatCollection : Form
/// <param name="e"></param>
private void ButtonCollectionDel_Click(object sender, EventArgs e)
{
// TODO прописать логику удаления элемента из коллекции
// нужно убедиться, что есть выбранная коллекция
// спросить у пользователя через MessageBox, что он подтверждает, что хочет удалить запись
// удалить и обновить ListBox
if (listBoxCollection.SelectedIndex < 0)
{
MessageBox.Show("Коллекция не выбрана");
@ -227,7 +228,7 @@ public partial class FormBoatCollection : 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);
@ -311,4 +312,24 @@ public partial class FormBoatCollection : Form
}
}
}
private void ButtonSortByType_Click(object sender, EventArgs e)
{
CompareBoats(new DrawningBoatCompareByType());
}
private void ButtonSortByColor_Click(object sender, EventArgs e)
{
CompareBoats(new DrawningBoatCompareByColor());
}
private void CompareBoats(IComparer<DrawningBoat?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}