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

This commit is contained in:
Никита Шипилов 2024-05-13 05:36:46 +04:00
parent 915c8cea9c
commit aaba1466fe
12 changed files with 332 additions and 43 deletions

View File

@ -26,7 +26,7 @@ public abstract class AbstractCompany
public static int? operator +(AbstractCompany company, DrawingPlane plane) public static int? operator +(AbstractCompany company, DrawingPlane plane)
{ {
return company._collection?.Insert(plane); return company._collection?.Insert(plane, new DrawingPlaneEqutables());
} }
public static DrawingPlane operator -(AbstractCompany company, int position) public static DrawingPlane operator -(AbstractCompany company, int position)
@ -63,4 +63,6 @@ public abstract class AbstractCompany
protected abstract void DrawBackgound(Graphics g); protected abstract void DrawBackgound(Graphics g);
protected abstract void SetObjectsPosition(); protected abstract void SetObjectsPosition();
public void Sort(IComparer<DrawingPlane?> 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 ProjectSeaplane.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

@ -7,9 +7,9 @@ public interface ICollectionGenericObjects<T>
int MaxCount { set; get; } int MaxCount { set; get; }
int Insert(T obj); int Insert(T obj, IEqualityComparer<T?>? comparer = null);
int Insert(T obj, int position); int Insert(T obj, int position, IEqualityComparer<T?>? comparer = null);
T Remove(int position); T Remove(int position);
@ -18,4 +18,6 @@ public interface ICollectionGenericObjects<T>
CollectionType GetCollectionType { get; } CollectionType GetCollectionType { get; }
IEnumerable<T?> GetItems(); IEnumerable<T?> GetItems();
void CollectionSort(IComparer<T?> comparer);
} }

View File

@ -39,14 +39,30 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[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); if (Count == _maxCount) throw new CollectionOverflowException(Count);
_collection.Add(obj); _collection.Add(obj);
return Count; 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 (Count == _maxCount) throw new CollectionOverflowException(Count);
if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position); if (position >= Count || position < 0) throw new PositionOutOfCollectionException(position);
_collection.Insert(position, obj); _collection.Insert(position, obj);
@ -67,4 +83,8 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i]; yield return _collection[i];
} }
} }
void ICollectionGenericObjects<T>.CollectionSort(IComparer<T?> comparer)
{
_collection.Sort(comparer);
}
} }

View File

@ -1,4 +1,5 @@
using ProjectSeaplane.Exceptions; using ProjectSeaplane.Drawings;
using ProjectSeaplane.Exceptions;
namespace ProjectSeaplane.CollectionGenericObjects; namespace ProjectSeaplane.CollectionGenericObjects;
@ -45,8 +46,17 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
return _collection[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<DrawingPlane>).Equals(obj as DrawingPlane, item as DrawingPlane))
throw new ObjectIsEqualException();
}
}
int index = 0; int index = 0;
while (index < _collection.Length) while (index < _collection.Length)
{ {
@ -59,8 +69,17 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
} }
throw new CollectionOverflowException(Count); 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<DrawingPlane>).Equals(obj as DrawingPlane, item as DrawingPlane))
throw new ObjectIsEqualException();
}
}
if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position); if (position >= _collection.Length || position < 0) throw new PositionOutOfCollectionException(position);
if (_collection[position] == null) if (_collection[position] == null)
{ {
@ -105,4 +124,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
yield return _collection[i]; yield return _collection[i];
} }
} }
void ICollectionGenericObjects<T>.CollectionSort(IComparer<T?> comparer)
{
Array.Sort(_collection, comparer);
}
} }

View File

@ -10,17 +10,17 @@ public class StorageCollection<T>
/// <summary> /// <summary>
/// Словарь (хранилище) с коллекциями /// Словарь (хранилище) с коллекциями
/// </summary> /// </summary>
readonly Dictionary<string, ICollectionGenericObjects<T>> _storages; readonly Dictionary<CollectionInfo, ICollectionGenericObjects<T>> _storages;
/// <summary> /// <summary>
/// Возвращение списка названий коллекций /// Возвращение списка названий коллекций
/// </summary> /// </summary>
public List<string> Keys => _storages.Keys.ToList(); public List<CollectionInfo> Keys => _storages.Keys.ToList();
/// <summary> /// <summary>
/// Конструктор /// Конструктор
/// </summary> /// </summary>
public StorageCollection() public StorageCollection()
{ {
_storages = new Dictionary<string, ICollectionGenericObjects<T>>(); _storages = new Dictionary<CollectionInfo, ICollectionGenericObjects<T>>();
} }
/// <summary> /// <summary>
/// Добавление коллекции в хранилище /// Добавление коллекции в хранилище
@ -29,14 +29,13 @@ public class StorageCollection<T>
/// <param name="collectionType">тип коллекции</param> /// <param name="collectionType">тип коллекции</param>
public void AddCollection(string name, CollectionType collectionType) public void AddCollection(string name, CollectionType collectionType)
{ {
// TODO проверка, что name не пустой и нет в словаре записи с таким ключом CollectionInfo collectionInfo = new CollectionInfo(name, collectionType, string.Empty);
// TODO Прописать логику для добавления if (_storages.ContainsKey(collectionInfo)) return;
if (_storages.ContainsKey(name)) return;
if (collectionType == CollectionType.None) return; if (collectionType == CollectionType.None) return;
else if (collectionType == CollectionType.Massive) else if (collectionType == CollectionType.Massive)
_storages[name] = new MassiveGenericObjects<T>(); _storages[collectionInfo] = new MassiveGenericObjects<T>();
else if (collectionType == CollectionType.List) else if (collectionType == CollectionType.List)
_storages[name] = new ListGenericObjects<T>(); _storages[collectionInfo] = new ListGenericObjects<T>();
} }
/// <summary> /// <summary>
/// Удаление коллекции /// Удаление коллекции
@ -44,10 +43,9 @@ public class StorageCollection<T>
/// <param name="name">Название коллекции</param> /// <param name="name">Название коллекции</param>
public void DelCollection(string name) public void DelCollection(string name)
{ {
CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
// TODO Прописать логику для удаления коллекции if (_storages.ContainsKey(collectionInfo))
if (_storages.ContainsKey(name)) _storages.Remove(collectionInfo);
_storages.Remove(name);
} }
/// <summary> /// <summary>
/// Доступ к коллекции /// Доступ к коллекции
@ -58,9 +56,9 @@ public class StorageCollection<T>
{ {
get get
{ {
// TODO Продумать логику получения объекта CollectionInfo collectionInfo = new CollectionInfo(name, CollectionType.None, string.Empty);
if (_storages.ContainsKey(name)) if (_storages.ContainsKey(collectionInfo))
return _storages[name]; return _storages[collectionInfo];
return null; return null;
} }
} }
@ -92,18 +90,17 @@ public class StorageCollection<T>
using (StreamWriter writer = new StreamWriter(filename)) using (StreamWriter writer = new StreamWriter(filename))
{ {
writer.Write(_collectionKey); writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages) foreach (KeyValuePair<CollectionInfo, ICollectionGenericObjects<T>> value in _storages)
{ {
StringBuilder sb = new(); StringBuilder sb = new();
sb.Append(Environment.NewLine); sb.Append(Environment.NewLine);
// не сохраняем пустые коллекции
if (value.Value.Count == 0) if (value.Value.Count == 0)
{ {
continue; continue;
} }
sb.Append(value.Key); sb.Append(value.Key);
sb.Append(_separatorForKeyValue); sb.Append(_separatorForKeyValue);
sb.Append(value.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.MaxCount); sb.Append(value.Value.MaxCount);
sb.Append(_separatorForKeyValue); sb.Append(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems()) foreach (T? item in value.Value.GetItems())
@ -149,25 +146,27 @@ public class StorageCollection<T>
while ((strs = fs.ReadLine()) != null) while ((strs = fs.ReadLine()) != null)
{ {
string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries); string[] record = strs.Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4) if (record.Length != 3)
{ {
continue; continue;
} }
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]); CollectionInfo? collectionInfo = CollectionInfo.GetCollectionInfo(record[0]) ??
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType); throw new Exception("Не удалось определить информацию коллекции: " + record[0]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionInfo.CollectionType) ??
throw new Exception("Не удалось создать коллекцию");
if (collection == null) if (collection == null)
{ {
throw new Exception("Не удалось создать коллекцию"); throw new Exception("Не удалось определить тип коллекции:" + record[1]);
} }
collection.MaxCount = Convert.ToInt32(record[2]); collection.MaxCount = Convert.ToInt32(record[1]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries); string[] set = record[2].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set) foreach (string elem in set)
{ {
if (elem?.CreateDrawningPlane() is T plane) if (elem?.CreateDrawningPlane() is T airplan)
{ {
try try
{ {
if (collection.Insert(plane) == -1) if (collection.Insert(airplan) == -1)
{ {
throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]); throw new Exception("Объект не удалось добавить в коллекцию: " + record[3]);
} }
@ -178,7 +177,7 @@ public class StorageCollection<T>
} }
} }
} }
_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 ProjectSeaplane.Drawings;
public class DrawingPlaneCompareByColor : IComparer<DrawingPlane?>
{
public int Compare(DrawingPlane? x, DrawingPlane? y)
{
if (x == null || x.EntityPlane == null)
{
return 1;
}
if (y == null || y.EntityPlane == null)
{
return -1;
}
var bodycolorCompare = x.EntityPlane.BodyColor.Name.CompareTo(y.EntityPlane.BodyColor.Name);
if (bodycolorCompare != 0)
{
return bodycolorCompare;
}
var speedCompare = x.EntityPlane.Speed.CompareTo(y.EntityPlane.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityPlane.Weight.CompareTo(y.EntityPlane.Weight);
}
}

View File

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectSeaplane.Drawings;
public class DrawingPlaneCompareByType : IComparer<DrawingPlane?>
{
public int Compare(DrawingPlane? x, DrawingPlane? y)
{
if (x == null || x.EntityPlane == null)
{
return 1;
}
if (y == null || y.EntityPlane == null)
{
return -1;
}
if (x.GetType().Name != y.GetType().Name)
{
return x.GetType().Name.CompareTo(y.GetType().Name);
}
var speedCompare = x.EntityPlane.Speed.CompareTo(y.EntityPlane.Speed);
if (speedCompare != 0)
{
return speedCompare;
}
return x.EntityPlane.Weight.CompareTo(y.EntityPlane.Weight);
}
}

View File

@ -0,0 +1,57 @@
using ProjectSeaplane.Entities;
using System.Diagnostics.CodeAnalysis;
namespace ProjectSeaplane.Drawings;
public class DrawingPlaneEqutables : IEqualityComparer<DrawingPlane?>
{
public bool Equals(DrawingPlane? x, DrawingPlane? y)
{
if (x == null || x.EntityPlane == null)
{
return false;
}
if (y == null || y.EntityPlane == null)
{
return false;
}
if (x.GetType().Name != y.GetType().Name)
{
return false;
}
if (x.EntityPlane.Speed != y.EntityPlane.Speed)
{
return false;
}
if (x.EntityPlane.Weight != y.EntityPlane.Weight)
{
return false;
}
if (x.EntityPlane.BodyColor != y.EntityPlane.BodyColor)
{
return false;
}
if (x is DrawingSeaplane && y is DrawingSeaplane)
{
EntitySeaplane _x = (EntitySeaplane)x.EntityPlane;
EntitySeaplane _y = (EntitySeaplane)x.EntityPlane;
if (_x.AdditionalColor != _y.AdditionalColor)
{
return false;
}
if (_x.Floats != _y.Floats)
{
return false;
}
if (_x.InflatableBoat != _y.InflatableBoat)
{
return false;
}
}
return true;
}
public int GetHashCode([DisallowNull] DrawingPlane obj)
{
return obj.GetHashCode();
}
}

View File

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

@ -52,6 +52,8 @@
loadToolStripMenuItem = new ToolStripMenuItem(); loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog(); saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog(); openFileDialog = new OpenFileDialog();
buttonSortByColor = new Button();
buttonSortByType = new Button();
groupBoxTools.SuspendLayout(); groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout(); panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout(); panelStorage.SuspendLayout();
@ -68,13 +70,15 @@
groupBoxTools.Dock = DockStyle.Right; groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(677, 24); groupBoxTools.Location = new Point(677, 24);
groupBoxTools.Name = "groupBoxTools"; groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(200, 583); groupBoxTools.Size = new Size(200, 678);
groupBoxTools.TabIndex = 0; groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false; groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты"; groupBoxTools.Text = "Инструменты";
// //
// panelCompanyTools // panelCompanyTools
// //
panelCompanyTools.Controls.Add(buttonSortByColor);
panelCompanyTools.Controls.Add(buttonSortByType);
panelCompanyTools.Controls.Add(buttonAddPlane); panelCompanyTools.Controls.Add(buttonAddPlane);
panelCompanyTools.Controls.Add(maskedTextBoxPosition); panelCompanyTools.Controls.Add(maskedTextBoxPosition);
panelCompanyTools.Controls.Add(buttonRefresh); panelCompanyTools.Controls.Add(buttonRefresh);
@ -83,7 +87,7 @@
panelCompanyTools.Enabled = false; panelCompanyTools.Enabled = false;
panelCompanyTools.Location = new Point(6, 346); panelCompanyTools.Location = new Point(6, 346);
panelCompanyTools.Name = "panelCompanyTools"; panelCompanyTools.Name = "panelCompanyTools";
panelCompanyTools.Size = new Size(188, 269); panelCompanyTools.Size = new Size(188, 332);
panelCompanyTools.TabIndex = 8; panelCompanyTools.TabIndex = 8;
// //
// buttonAddPlane // buttonAddPlane
@ -107,7 +111,7 @@
// //
// buttonRefresh // buttonRefresh
// //
buttonRefresh.Location = new Point(3, 197); buttonRefresh.Location = new Point(3, 173);
buttonRefresh.Name = "buttonRefresh"; buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(182, 41); buttonRefresh.Size = new Size(182, 41);
buttonRefresh.TabIndex = 6; buttonRefresh.TabIndex = 6;
@ -117,7 +121,7 @@
// //
// buttonDelPlane // buttonDelPlane
// //
buttonDelPlane.Location = new Point(3, 107); buttonDelPlane.Location = new Point(3, 79);
buttonDelPlane.Name = "buttonDelPlane"; buttonDelPlane.Name = "buttonDelPlane";
buttonDelPlane.Size = new Size(182, 41); buttonDelPlane.Size = new Size(182, 41);
buttonDelPlane.TabIndex = 4; buttonDelPlane.TabIndex = 4;
@ -127,7 +131,7 @@
// //
// buttonGoToCheck // buttonGoToCheck
// //
buttonGoToCheck.Location = new Point(3, 154); buttonGoToCheck.Location = new Point(3, 126);
buttonGoToCheck.Name = "buttonGoToCheck"; buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(182, 41); buttonGoToCheck.Size = new Size(182, 41);
buttonGoToCheck.TabIndex = 5; buttonGoToCheck.TabIndex = 5;
@ -244,7 +248,7 @@
pictureBox.Dock = DockStyle.Fill; pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 24); pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox"; pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(677, 583); pictureBox.Size = new Size(677, 678);
pictureBox.TabIndex = 1; pictureBox.TabIndex = 1;
pictureBox.TabStop = false; pictureBox.TabStop = false;
// //
@ -288,11 +292,31 @@
// //
openFileDialog.Filter = "txt file | *.txt"; openFileDialog.Filter = "txt file | *.txt";
// //
// buttonSortByColor
//
buttonSortByColor.Location = new Point(3, 267);
buttonSortByColor.Name = "buttonSortByColor";
buttonSortByColor.Size = new Size(182, 41);
buttonSortByColor.TabIndex = 8;
buttonSortByColor.Text = "Соритровать по цвету";
buttonSortByColor.UseVisualStyleBackColor = true;
buttonSortByColor.Click += buttonSortByColor_Click;
//
// buttonSortByType
//
buttonSortByType.Location = new Point(3, 220);
buttonSortByType.Name = "buttonSortByType";
buttonSortByType.Size = new Size(182, 41);
buttonSortByType.TabIndex = 7;
buttonSortByType.Text = "Сортировать по типу";
buttonSortByType.UseVisualStyleBackColor = true;
buttonSortByType.Click += buttonSortByType_Click;
//
// FormSeaplaneCollection // FormSeaplaneCollection
// //
AutoScaleDimensions = new SizeF(7F, 15F); AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font; AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(877, 607); ClientSize = new Size(877, 702);
Controls.Add(pictureBox); Controls.Add(pictureBox);
Controls.Add(groupBoxTools); Controls.Add(groupBoxTools);
Controls.Add(menuStrip); Controls.Add(menuStrip);
@ -337,5 +361,7 @@
private ToolStripMenuItem loadToolStripMenuItem; private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog; private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog; private OpenFileDialog openFileDialog;
private Button buttonSortByColor;
private Button buttonSortByType;
} }
} }

View File

@ -185,7 +185,7 @@ public partial class FormSeaplaneCollection : Form
listBoxCollection.Items.Clear(); listBoxCollection.Items.Clear();
for (int i = 0; i < _storageCollection.Keys?.Count; ++i) for (int i = 0; i < _storageCollection.Keys?.Count; ++i)
{ {
string? colName = _storageCollection.Keys?[i]; string? colName = _storageCollection.Keys?[i].Name;
if (!string.IsNullOrEmpty(colName)) if (!string.IsNullOrEmpty(colName))
{ {
listBoxCollection.Items.Add(colName); listBoxCollection.Items.Add(colName);
@ -255,4 +255,24 @@ public partial class FormSeaplaneCollection : Form
} }
} }
} }
private void buttonSortByType_Click(object sender, EventArgs e)
{
ComparePlane(new DrawingPlaneCompareByType());
}
private void buttonSortByColor_Click(object sender, EventArgs e)
{
ComparePlane(new DrawingPlaneCompareByColor());
}
private void ComparePlane(IComparer<DrawingPlane?> comparer)
{
if (_company == null)
{
return;
}
_company.Sort(comparer);
pictureBox.Image = _company.Show();
}
} }