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

This commit is contained in:
Aidar 2024-06-05 22:02:13 +04:00
parent ba1621ee9f
commit ae2a71ad80
12 changed files with 385 additions and 76 deletions

View File

@ -1,5 +1,4 @@
using ProjectLiner.Drawnings;
using ProjectLiner.Exceptions;
namespace ProjectLiner.CollectionGenericObjects;
@ -64,7 +63,7 @@ public abstract class AbstractCompany
{
return -1;
}
return company._collection.Insert(ship);
return company._collection.Insert(ship, new DrawiningShipEqutables());
}
/// <summary>
@ -117,6 +116,12 @@ public abstract class AbstractCompany
return bitmap;
}
/// <summary>
/// Сортировка
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
public void Sort(IComparer<DrawningShip?> comparer) => _collection?.CollectionSort(comparer);
/// <summary>
/// Вывод заднего фона
/// </summary>

View File

@ -0,0 +1,78 @@
namespace ProjectLiner.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

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

View File

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

View File

@ -21,8 +21,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public int Count => _collection.Count;
public int MaxCount
{
public int MaxCount {
get
{
return _maxCount;
@ -57,21 +56,21 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
}
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
return Insert(obj, Count);
return Insert(obj, Count, comparer);
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (_collection.Contains(obj, comparer))
{
throw new ObjectNotUniqueException();
}
if (Count >= _maxCount)
{
throw new CollectionOverflowException(Count);
}
if (position > _collection.Count || position < 0)
{
throw new PositionOutOfCollectionException();
}
_collection.Insert(position, obj);
return Count;
}
@ -97,4 +96,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 ProjectLiner.Exceptions;
using ProjectLiner.Drawnings;
namespace ProjectLiner.CollectionGenericObjects;
@ -52,10 +53,6 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
{
try
{
if (_collection[position] == null)
{
throw new ObjectNotFoundException();
}
return _collection[position];
}
catch (IndexOutOfRangeException)
@ -64,17 +61,25 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
}
public int Insert(T obj)
public int Insert(T obj, IEqualityComparer<T?>? comparer = null)
{
return Insert(obj, 0);
return Insert(obj, 0, comparer);
}
public int Insert(T obj, int position)
public int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null)
{
if (position < 0 || position > _collection.Length - 1)
{
throw new PositionOutOfCollectionException();
}
if (comparer != null)
{
foreach (T? item in _collection)
{
if ((comparer as IEqualityComparer<DrawningShip>).Equals(obj as DrawningShip, item as DrawningShip))
throw new ObjectNotUniqueException();
}
}
for (int i = position; i < Count; i++)
{
if (_collection[i] == null)
@ -119,4 +124,10 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
public void CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
Array.Reverse(_collection);
}
}

View File

@ -1,5 +1,6 @@
using ProjectLiner.Drawnings;
using ProjectLiner.Exceptions;
using System.IO;
namespace ProjectLiner.CollectionGenericObjects;
@ -29,19 +30,19 @@ 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>
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
_storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
}
/// <summary>
@ -51,21 +52,20 @@ public class StorageCollection<T>
/// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType)
{
if (string.IsNullOrEmpty(name) || _storages.ContainsKey(name))
CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
if (collectionInfo.Name == null || _storages.ContainsKey(collectionInfo))
{
return;
}
if (collectionType == CollectionType.None)
{
switch (collectionType){
case CollectionType.None:
return;
case CollectionType.Massive:
_storages.Add(collectionInfo, new MassiveGenericObjects<T> { });
return;
case CollectionType.List:
_storages.Add(collectionInfo, new ListGenericObjects<T> { });
return;
}
if (collectionType == CollectionType.Massive)
{
_storages[name] = new MassiveGenericObjects<T>();
}
else if (collectionType == CollectionType.List)
{
_storages[name] = new ListGenericObjects<T>();
}
}
@ -75,11 +75,12 @@ public class StorageCollection<T>
/// <param name="name">Название коллекции</param>
public void DelCollection(string name)
{
if (name == null || !_storages.ContainsKey(name))
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (collectionInfo.Name == null || !_storages.ContainsKey(collectionInfo))
{
return;
}
_storages.Remove(name);
_storages.Remove(collectionInfo);
}
/// <summary>
@ -91,14 +92,12 @@ public class StorageCollection<T>
{
get
{
if (_storages.ContainsKey(name))
{
return _storages[name];
}
else
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (collectionInfo == null || !_storages.ContainsKey(collectionInfo))
{
return null;
}
return _storages[collectionInfo];
}
}
@ -120,16 +119,17 @@ public class StorageCollection<T>
using (StreamWriter writer = new StreamWriter(filename))
{
writer.WriteLine(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{
writer.Write($"{value.Key}{_separatorForKeyValue}{value.Value.GetCollectionType}{_separatorForKeyValue}{value.Value.MaxCount}{_separatorForKeyValue}");
writer.Write($"{value.Key}{_separatorForKeyValue}{value.Value.MaxCount}{_separatorForKeyValue}");
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (!string.IsNullOrEmpty(data))
{
writer.WriteLine(data);
writer.Write(data);
writer.Write(_separatorItems);
}
}
}
@ -165,22 +165,18 @@ public class StorageCollection<T>
while (line != null)
{
string[] record = line.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
if (record.Length != 3)
{
line = reader.ReadLine();
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
throw new Exception("Не удалось определить информацию коллекции: " + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
throw new InvalidCastException("Не удалось создать коллекцию");
}
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)
{
@ -197,7 +193,7 @@ public class StorageCollection<T>
}
}
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
line = reader.ReadLine();
}
}

View File

@ -0,0 +1,61 @@
using ProjectLiner.Entities;
using System.Diagnostics.CodeAnalysis;
namespace ProjectLiner.Drawnings;
/// <summary>
/// Реализация сравнения двух объектов класса-прорисовки
/// </summary>
public class DrawiningShipEqutables : IEqualityComparer<DrawningShip?>
{
public bool Equals(DrawningShip? x, DrawningShip? y)
{
if (x == null || x.EntityShip == null)
{
return false;
}
if (y == null || y.EntityShip == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityShip.Speed != y.EntityShip.Speed)
{
return false;
}
if (x.EntityShip.Weight != y.EntityShip.Weight)
{
return false;
}
if (x.EntityShip.BodyColor != y.EntityShip.BodyColor)
{
return false;
}
if (x is DrawningLiner && y is DrawningLiner)
{
EntityLiner _x = (EntityLiner)x.EntityShip;
EntityLiner _y = (EntityLiner)x.EntityShip;
if (_x.AdditionalColor != _y.AdditionalColor)
{
return false;
}
if (_x.SecondDeck != _y.SecondDeck)
{
return false;
}
if (_x.Pool != _y.Pool)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningShip obj)
{
return obj.GetHashCode();
}
}

View File

@ -0,0 +1,37 @@
namespace ProjectLiner.Drawnings;
/// <summary>
/// Сравнение по цвету, скорости, весу
/// </summary>
public class DrawningShipCompareByColor : IComparer<DrawningShip?>
{
public int Compare(DrawningShip? x, DrawningShip? y)
{
if (x == null && y == null)
{
return 0;
}
if (x == null || x.EntityShip == null)
{
return -1;
}
if (y == null || y.EntityShip == null)
{
return 1;
}
var bodycolorCompare = y.EntityShip.BodyColor.Name.CompareTo(x.EntityShip.BodyColor.Name);
if (bodycolorCompare != 0)
{
return bodycolorCompare;
}
var speedCompare = y.EntityShip.Speed.CompareTo(x.EntityShip.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return y.EntityShip.Weight.CompareTo(x.EntityShip.Weight);
}
}

View File

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

View File

@ -34,6 +34,8 @@ namespace ProjectLiner
{
groupBoxTools = new GroupBox();
panelCompanyTools = new Panel();
buttonSortByColor = new Button();
buttonSortByType = new Button();
buttonAddShip = new Button();
buttonRefresh = new Button();
maskedTextBoxPosition = new MaskedTextBox();
@ -72,13 +74,15 @@ namespace ProjectLiner
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(793, 24);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(144, 547);
groupBoxTools.Size = new Size(144, 588);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddShip);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(maskedTextBoxPosition);
@ -88,9 +92,29 @@ namespace ProjectLiner
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(3, 321);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(138, 223);
panelCompanyTools.Size = new Size(138, 264);
panelCompanyTools.TabIndex = 10;
//
// buttonSortByColor
//
buttonSortByColor.Location = new Point(4, 218);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(126, 43);
buttonSortByColor.TabIndex = 8;
buttonSortByColor.Text = "Сортировка по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += ButtonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Location = new Point(4, 182);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(126, 30);
buttonSortByType.TabIndex = 7;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += ButtonSortByType_Click;
//
// buttonAddShip
//
buttonAddShip.Location = new Point(4, 3);
@ -103,9 +127,9 @@ namespace ProjectLiner
//
// buttonRefresh
//
buttonRefresh.Location = new Point(4, 172);
buttonRefresh.Location = new Point(3, 153);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(126, 42);
buttonRefresh.Size = new Size(126, 26);
buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
@ -113,7 +137,7 @@ namespace ProjectLiner
//
// maskedTextBoxPosition
//
maskedTextBoxPosition.Location = new Point(4, 71);
maskedTextBoxPosition.Location = new Point(3, 52);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(126, 23);
@ -122,7 +146,7 @@ namespace ProjectLiner
//
// buttonGoToCheck
//
buttonGoToCheck.Location = new Point(4, 136);
buttonGoToCheck.Location = new Point(3, 117);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(126, 30);
buttonGoToCheck.TabIndex = 5;
@ -132,7 +156,7 @@ namespace ProjectLiner
//
// buttonRemoveShip
//
buttonRemoveShip.Location = new Point(4, 100);
buttonRemoveShip.Location = new Point(3, 81);
buttonRemoveShip.Name = "buttonRemoveShip";
buttonRemoveShip.Size = new Size(126, 30);
buttonRemoveShip.TabIndex = 4;
@ -251,7 +275,7 @@ namespace ProjectLiner
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(793, 547);
pictureBox.Size = new Size(793, 588);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
@ -299,7 +323,7 @@ namespace ProjectLiner
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(937, 571);
ClientSize = new Size(937, 612);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
@ -344,5 +368,7 @@ namespace ProjectLiner
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
}
}

View File

@ -215,7 +215,7 @@ public partial class FormShipCollection : 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);
@ -302,4 +302,38 @@ public partial class FormShipCollection : Form
RefreshListBoxItems();
}
}
/// <summary>
/// Сортировка по типу
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByType_Click(object sender, EventArgs e)
{
CompareShips(new DrawningShipCompareByType());
}
/// <summary>
/// Сортировка по цвету
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ButtonSortByColor_Click(object sender, EventArgs e)
{
CompareShips(new DrawningShipCompareByColor());
}
/// <summary>
/// Сортировка по сравнителю
/// </summary>
/// <param name="comparer">Сравнитель объектов</param>
private void CompareShips(IComparer<DrawningShip?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}