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

This commit is contained in:
nezui1 2024-04-22 18:03:58 +04:00
parent d5fc3fd5ec
commit 5d662983bd
13 changed files with 448 additions and 44 deletions

View File

@ -50,7 +50,7 @@ public abstract class AbstractCompany
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.SetMaxCount = GetMaxCount - 4;
_collection.MaxCount = GetMaxCount - 4;
}
/// <summary>

View File

@ -1,4 +1,5 @@
using System;
using ProjectAirFighter.CollectionGenericObjects;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
@ -19,9 +20,9 @@ public interface ICollectionGenericObjects<T>
int Count { get; }
/// <summary>
///Установка максимального количества элементов
/// Установка максимального количества элементов
/// </summary>
int SetMaxCount { set; }
int MaxCount { get; set; }
/// <summary>
/// Добавление объекта в коллекцию
@ -50,4 +51,15 @@ public interface ICollectionGenericObjects<T>
/// <param name="position"></param>
/// <returns></returns>
T? Get(int position);
/// <summary>
/// Получение типа коллекции
/// </summary>
CollectionType GetCollectionType { get; }
/// <summary>
/// Получение объектов коллекции по одному
/// </summary>
/// <returns>Поэлемениный вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
}

View File

@ -26,7 +26,24 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public int Count => _collection.Count;
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } }
public CollectionType GetCollectionType => CollectionType.List;
public int MaxCount {
get
{
return _maxCount;
}
set
{
if (value > 0)
{
_maxCount = value;
}
}
}
/// <summary>
/// Конструктор
@ -80,4 +97,12 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
_collection.RemoveAt(position);
return temp;
}
public IEnumerable<T?> GetItems()
{
for(int i = 0; i < _collection.Count; ++i)
{
yield return _collection[i];
}
}
}

View File

@ -21,23 +21,31 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
public int Count => _collection.Length;
public int SetMaxCount
public int MaxCount
{
get
{
return _collection.Length;
}
set
{
if (value > 0)
{
if (Count > 0)
if (_collection.Length > 0)
{
Array.Resize(ref _collection, value);
}
else {
else
{
_collection = new T?[value];
}
}
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary>
/// Конструктор
/// </summary>
@ -118,4 +126,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
_collection[position] = null;
return temp;
}
public IEnumerable<T?> GetItems()
{
for(int i = 0; i < _collection.Length; ++i)
{
yield return _collection[i];
}
}
}

View File

@ -1,4 +1,5 @@
using ProjectAirFighter.CollectionGenericObject;
using ProjectAirFighter.Drawning;
using System;
using System.Collections.Generic;
using System.Linq;
@ -12,7 +13,7 @@ namespace ProjectAirFighter.CollectionGenericObjects;
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : class
where T : DrawningWarPlane
{
/// <summary>
/// Словарь (хранилище) с коллекциями
@ -23,7 +24,22 @@ public class StorageCollection<T>
/// Возвращение списка названий коллекций
/// </summary>
public List<string> Keys => _storages.Keys.ToList();
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionsStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
public StorageCollection()
{
_storages = new Dictionary<string, ICollectionGenericObjects<T>>();
@ -82,15 +98,121 @@ public class StorageCollection<T>
}
}
public ICollectionGenericObjects<T>? this[int index]
{
get
{
//логика получения объекта
if (index > Keys.Count || index < 0)
return null;
return _storages[Keys[index]];
public bool SaveData(string filename)
{
if (_storages.Count == 0)
return false;
if (File.Exists(filename))
File.Delete(filename);
using FileStream fs = new(filename, FileMode.Create);
using StreamWriter sw = new StreamWriter(fs);
sw.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{
sw.Write(Environment.NewLine);
if (value.Value.Count == 0)
{
continue;
}
sw.Write(value.Key);
sw.Write(_separatorForKeyValue);
sw.Write(value.Value.GetCollectionType);
sw.Write(_separatorForKeyValue);
sw.Write(value.Value.MaxCount);
sw.Write(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
sw.Write(data);
sw.Write(_separatorItems);
}
}
return true;
}
}
/// <summary>
/// Загрузка информации по самолетам в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
}
using (FileStream fs = new(filename, FileMode.Open))
{
using StreamReader sr = new StreamReader(fs);
string str = sr.ReadLine();
if (str == null || str.Length == 0)
{
return false;
}
if (!str.Equals(_collectionKey))
{
return false;
}
_storages.Clear();
while (!sr.EndOfStream)
{
string[] record = sr.ReadLine().Split(_separatorForKeyValue, StringSplitOptions.RemoveEmptyEntries);
if (record.Length != 4)
{
continue;
}
CollectionType collectionType = (CollectionType)Enum.Parse(typeof(CollectionType), record[1]);
ICollectionGenericObjects<T>? collection = StorageCollection<T>.CreateCollection(collectionType);
if (collection == null)
{
return false;
}
collection.MaxCount = Convert.ToInt32(record[2]);
string[] set = record[3].Split(_separatorItems, StringSplitOptions.RemoveEmptyEntries);
foreach (string elem in set)
{
if (elem?.CreateDrawningWarPlane() is T warPlane)
{
if (collection.Insert(warPlane) == -1)
return false;
}
}
_storages.Add(record[0], collection);
}
}
return true;
}
/// <summary>
/// Создание коллекции по типу
/// </summary>
/// <param name="collectionType"></param>
/// <returns></returns>
private static ICollectionGenericObjects<T>?
CreateCollection(CollectionType collectionType)
{
return collectionType switch
{
CollectionType.Massive => new MassiveGenericObjects<T>(),
CollectionType.List => new ListGenericObjects<T>(),
_ => null,
};
}
}

View File

@ -27,6 +27,16 @@ public class DrawningAirFighter : DrawningWarPlane
}
/// <summary>
/// Конструктор для метода создания объекта из строки (ExtentionDrawningWarPlane)
/// </summary>
/// <param name="warPlane"></param>
public DrawningAirFighter(EntityWarPlane? warPlane) : base(warPlane)
{
if (warPlane != null)
EntityWarPlane = warPlane;
}
public override void DrawTransport(Graphics g)
{

View File

@ -93,6 +93,15 @@ public class DrawningWarPlane
}
/// <summary>
/// Конструктор для метода создания объекта из строки (ExtentionDrawningWarPlane)
/// </summary>
/// <param name="warPlane"></param>
public DrawningWarPlane(EntityWarPlane? warPlane) : this()
{
EntityWarPlane = warPlane;
}
/// <summary>
/// Установка границ поля

View File

@ -0,0 +1,60 @@
using ProjectAirFighter.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectAirFighter.Drawning;
public static class ExtetntionDrawningWarPlane
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningWarPlane? CreateDrawningWarPlane(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityWarPlane? warPlane = EntityAirFighter.CreateEntityAirFighter(strs);
if (warPlane != null)
{
return new DrawningAirFighter(warPlane);
}
warPlane = EntityWarPlane.CreateEntityWarPlane(strs);
if (warPlane != null)
{
return new DrawningWarPlane(warPlane);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningWarPlane">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningWarPlane drawningWarPlane)
{
string[]? array = drawningWarPlane?.EntityWarPlane?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@ -4,21 +4,6 @@
/// </summary>
public class EntityAirFighter : EntityWarPlane
{
/// <summary>
/// Скорость
/// </summary>
public int Speed { get; private set; }
/// <summary>
/// Вес
/// </summary>
public double Weight { get; private set; }
/// <summary>
/// Основной цвет
/// </summary>
public Color BodyColor { get; private set; }
/// <summary>
/// Дополнительный цвет
/// </summary>
@ -62,6 +47,34 @@ public class EntityAirFighter : EntityWarPlane
AdditionalWing = additionalWing;
}
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityAirFighter), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name,
Rocket.ToString(), AdditionalWing.ToString()};
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityAirFighter? CreateEntityAirFighter(string[] strs)
{
if (strs.Length != 7 || strs[0] != nameof(EntityAirFighter))
{
return null;
}
return new EntityAirFighter(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4]),
Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]));
}
}

View File

@ -45,4 +45,31 @@ public class EntityWarPlane
Weight = weight;
BodyColor = bodyColor;
}
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public virtual string[] GetStringRepresentation()
{
return new[] {nameof(EntityWarPlane),Speed.ToString(), Weight.ToString(), BodyColor.Name};
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityWarPlane? CreateEntityWarPlane(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(EntityWarPlane))
{
return null;
}
return new EntityWarPlane(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]));
}
}

View File

@ -46,10 +46,17 @@
labelCollectionName = new Label();
comboBoxSelectorCompany = new ComboBox();
pictureBox = new PictureBox();
menuStrip = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
saveToolStripMenuItem = new ToolStripMenuItem();
loadToolStripMenuItem = new ToolStripMenuItem();
saveFileDialog = new SaveFileDialog();
openFileDialog = new OpenFileDialog();
groupBox1.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
// groupBox1
@ -59,9 +66,9 @@
groupBox1.Controls.Add(panelStorage);
groupBox1.Controls.Add(comboBoxSelectorCompany);
groupBox1.Dock = DockStyle.Right;
groupBox1.Location = new Point(659, 0);
groupBox1.Location = new Point(659, 24);
groupBox1.Name = "groupBox1";
groupBox1.Size = new Size(174, 663);
groupBox1.Size = new Size(174, 658);
groupBox1.TabIndex = 0;
groupBox1.TabStop = false;
groupBox1.Text = "Инструменты";
@ -235,19 +242,61 @@
// pictureBox
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Location = new Point(0, 0);
pictureBox.Location = new Point(0, 24);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(659, 663);
pictureBox.Size = new Size(659, 658);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
// menuStrip
//
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(833, 24);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip1";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(48, 20);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(181, 22);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += saveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(181, 22);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += loadToolStripMenuItem_Click_1;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// openFileDialog
//
openFileDialog.Filter = "txt file | *.txt";
//
// FormWarPlaneCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(833, 663);
ClientSize = new Size(833, 682);
Controls.Add(pictureBox);
Controls.Add(groupBox1);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormWarPlaneCollection";
Text = "Коллекция военных самолетов";
groupBox1.ResumeLayout(false);
@ -256,7 +305,10 @@
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
@ -279,5 +331,11 @@
private Button buttonCreateCompany;
private Button buttonCollectionRemove;
private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
}
}

View File

@ -44,18 +44,19 @@ public partial class FormWarPlaneCollection : Form
panelCompanyTools.Enabled = false;
}
private void ButtonAddWarPlane_Click(object sender, EventArgs e){
private void ButtonAddWarPlane_Click(object sender, EventArgs e)
{
FormWarPlaneConfig form = new();
form.Show();
form.AddEvent(SetWarPlane);
}
private void SetWarPlane(DrawningWarPlane warPlane)
private void SetWarPlane(DrawningWarPlane warPlane)
{
if (_company == null || warPlane == null)
if (_company == null || warPlane == null)
{
return;
}
@ -231,7 +232,49 @@ public partial class FormWarPlaneCollection : Form
}
/// <summary>
/// Обработка нажатия "Сохранение"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.SaveData(saveFileDialog.FileName))
{
MessageBox.Show("Сохранение прошло успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Не сохраненилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
/// <summary>
/// Обработка нажатия "Загрузка"
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void loadToolStripMenuItem_Click_1(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
{
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
RerfreshListBoxItems();
}
else
{
MessageBox.Show("Не сохранилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}

View File

@ -117,4 +117,13 @@
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="menuStrip.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>126, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>261, 17</value>
</metadata>
</root>