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

This commit is contained in:
IlyasValiulov 2024-05-12 21:22:40 +04:00
parent af6b779070
commit c137f81fa8
13 changed files with 337 additions and 46 deletions

View File

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

View File

@ -0,0 +1,43 @@
namespace ProjectWarmlyShip.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

@ -1,4 +1,6 @@
namespace ProjectWarmlyShip.CollectionGenericObjects;
using ProjectWarmlyShip.Drawnings;
namespace ProjectWarmlyShip.CollectionGenericObjects;
public interface ICollectionGenericObjects<T>
where T : class
@ -15,15 +17,17 @@ 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>
/// Удаление объекта из коллекции с конкретной позиции
/// </summary>
@ -45,4 +49,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,4 +1,7 @@
using ProjectWarmlyShip.Exceptions;
using ProjectWarmlyShip.Drawnings;
using ProjectWarmlyShip.Exceptions;
using System.Linq;
using System.Runtime.Serialization;
namespace ProjectWarmlyShip.CollectionGenericObjects;
@ -40,14 +43,28 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
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();
}
}
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)
{
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);
@ -67,4 +84,9 @@ 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 ProjectWarmlyShip.Exceptions;
using ProjectWarmlyShip.Drawnings;
using ProjectWarmlyShip.Exceptions;
namespace ProjectWarmlyShip.CollectionGenericObjects;
@ -45,8 +46,16 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
if (_collection[position] == null) throw new ObjectNotFoundException(position);
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<DrawningShip>).Equals(obj as DrawningShip, item as DrawningShip))
throw new ObjectIsEqualException();
}
}
int index = 0;
while (index < _collection.Length)
{
@ -59,8 +68,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<DrawningShip>).Equals(obj as DrawningShip, item as DrawningShip))
throw new ObjectIsEqualException();
}
}
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) {
_collection[position] = obj;
@ -103,4 +120,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i];
}
}
void ICollectionGenericObjects<T>.CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
}

View File

@ -9,17 +9,17 @@ 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>
/// Добавление коллекции в хранилище
@ -28,12 +28,13 @@ public class StorageCollection<T>
/// <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>
/// Удаление коллекции
@ -41,8 +42,9 @@ public class StorageCollection<T>
/// <param name="name">Название коллекции</param>
public void DelCollection(string name)
{
if (_storages.ContainsKey(name))
_storages.Remove(name);
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(collectionInfo))
_storages.Remove(collectionInfo);
}
/// <summary>
/// Доступ к коллекции
@ -53,8 +55,9 @@ public class StorageCollection<T>
{
get
{
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;
}
}
@ -87,7 +90,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)
@ -96,8 +99,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())
@ -139,18 +140,20 @@ public class StorageCollection<T>
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?.CreateDrawningShip() is T ship)
@ -168,7 +171,7 @@ public class StorageCollection<T>
}
}
}
_storages.Add(record[0], collection);
_storages.Add(collectionInfo, collection);
}
}
}

View File

@ -0,0 +1,57 @@
using ProjectWarmlyShip.Entities;
using System.Diagnostics.CodeAnalysis;
namespace ProjectWarmlyShip.Drawnings;
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 DrawningWarmlyShip && y is DrawningWarmlyShip)
{
EntityWarmlyShip _x = (EntityWarmlyShip)x.EntityShip;
EntityWarmlyShip _y = (EntityWarmlyShip)x.EntityShip;
if (_x.AdditionalColor != _y.AdditionalColor)
{
return false;
}
if (_x.ShipPipes != _y.ShipPipes)
{
return false;
}
if (_x.FuelTank != _y.FuelTank)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawningShip obj)
{
return obj.GetHashCode();
}
}

View File

@ -0,0 +1,28 @@
namespace ProjectWarmlyShip.Drawnings;
public class DrawningShipCompareByColor : IComparer<DrawningShip?>
{
public int Compare(DrawningShip? x, DrawningShip? y)
{
if (x == null || x.EntityShip == null)
{
return 1;
}
if (y == null || y.EntityShip == null)
{
return -1;
}
var bodycolorCompare = x.EntityShip.BodyColor.Name.CompareTo(y.EntityShip.BodyColor.Name);
if (bodycolorCompare != 0)
{
return bodycolorCompare;
}
var speedCompare = x.EntityShip.Speed.CompareTo(y.EntityShip.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityShip.Weight.CompareTo(y.EntityShip.Weight);
}
}

View File

@ -0,0 +1,29 @@
namespace ProjectWarmlyShip.Drawnings;
public class DrawningShipCompareByType : IComparer<DrawningShip?>
{
public int Compare(DrawningShip? x, DrawningShip? y)
{
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

@ -0,0 +1,16 @@
using System.Runtime.Serialization;
namespace ProjectWarmlyShip.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

@ -30,6 +30,8 @@
{
groupBoxTools = new GroupBox();
panelCompanyTools = new Panel();
buttonByColor = new Button();
buttonSortByType = new Button();
buttonAddShip = new Button();
buttonRefresh = new Button();
maskedTextBox = new MaskedTextBox();
@ -67,13 +69,15 @@
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(887, 24);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(146, 597);
groupBoxTools.Size = new Size(146, 600);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
//
// panelCompanyTools
//
panelCompanyTools.Controls.Add(buttonByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddShip);
panelCompanyTools.Controls.Add(buttonRefresh);
panelCompanyTools.Controls.Add(maskedTextBox);
@ -82,9 +86,33 @@
panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(6, 333);
panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(200, 280);
panelCompanyTools.Size = new Size(200, 249);
panelCompanyTools.TabIndex = 2;
//
// buttonByColor
//
buttonByColor.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonByColor.Font = new Font("Segoe UI", 8.25F, FontStyle.Regular, GraphicsUnit.Point);
buttonByColor.Location = new Point(4, 211);
buttonByColor.Name = "buttonByColor";
buttonByColor.Size = new Size(133, 29);
buttonByColor.TabIndex = 8;
buttonByColor.Text = "Сортировка по цвету";
buttonByColor.TextAlign = ContentAlignment.MiddleLeft;
buttonByColor.UseVisualStyleBackColor = true;
buttonByColor.Click += buttonByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonSortByType.Location = new Point(4, 176);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(133, 29);
buttonSortByType.TabIndex = 7;
buttonSortByType.Text = "Сортировка по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// buttonAddShip
//
buttonAddShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
@ -98,10 +126,9 @@
//
// buttonRefresh
//
buttonRefresh.Anchor = AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
buttonRefresh.Location = new Point(3, 214);
buttonRefresh.Location = new Point(4, 144);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(128, 40);
buttonRefresh.Size = new Size(130, 26);
buttonRefresh.TabIndex = 6;
buttonRefresh.Text = "Обновить";
buttonRefresh.UseVisualStyleBackColor = true;
@ -109,7 +136,7 @@
//
// maskedTextBox
//
maskedTextBox.Location = new Point(3, 93);
maskedTextBox.Location = new Point(3, 47);
maskedTextBox.Mask = "00";
maskedTextBox.Name = "maskedTextBox";
maskedTextBox.Size = new Size(128, 23);
@ -119,9 +146,9 @@
// buttonGoToCheck
//
buttonGoToCheck.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonGoToCheck.Location = new Point(3, 168);
buttonGoToCheck.Location = new Point(4, 109);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(128, 40);
buttonGoToCheck.Size = new Size(128, 29);
buttonGoToCheck.TabIndex = 5;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
@ -130,9 +157,9 @@
// buttonRemoveShip
//
buttonRemoveShip.Anchor = AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right;
buttonRemoveShip.Location = new Point(3, 122);
buttonRemoveShip.Location = new Point(3, 76);
buttonRemoveShip.Name = "buttonRemoveShip";
buttonRemoveShip.Size = new Size(128, 40);
buttonRemoveShip.Size = new Size(128, 27);
buttonRemoveShip.TabIndex = 4;
buttonRemoveShip.Text = "Удаление";
buttonRemoveShip.UseVisualStyleBackColor = true;
@ -248,7 +275,7 @@
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(887, 597);
pictureBox.Size = new Size(887, 600);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
@ -296,7 +323,7 @@
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1033, 621);
ClientSize = new Size(1033, 624);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
@ -341,5 +368,7 @@
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
private Button buttonByColor;
private Button buttonSortByType;
}
}

View File

@ -48,6 +48,11 @@ public partial class FormShipCollection : Form
MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
catch (ObjectIsEqualException ex)
{
MessageBox.Show("Не удалось добавить объект");
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
private void buttonRemoveShip_Click(object sender, EventArgs e)
{
@ -146,7 +151,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);
@ -170,7 +175,8 @@ public partial class FormShipCollection : Form
RerfreshListBoxItems();
_logger.LogInformation("Коллекция: " + listBoxCollection.SelectedItem.ToString() + " удалена");
}
catch (Exception ex) {
catch (Exception ex)
{
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
@ -225,12 +231,30 @@ public partial class FormShipCollection : Form
RerfreshListBoxItems();
_logger.LogInformation("Загрузка из файла: {filename}", openFileDialog.FileName);
}
catch(Exception ex)
catch (Exception ex)
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
_logger.LogError("Ошибка: {Message}", ex.Message);
}
}
}
private void buttonSortByType_Click(object sender, EventArgs e)
{
CompareShip(new DrawningShipCompareByType());
}
private void buttonByColor_Click(object sender, EventArgs e)
{
CompareShip(new DrawningShipCompareByColor());
}
private void CompareShip(IComparer<DrawningShip?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
}

View File

@ -126,4 +126,7 @@
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>261, 17</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>68</value>
</metadata>
</root>