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

This commit is contained in:
nikos77781 2024-05-21 01:07:39 +04:00
parent bc218c4adf
commit 8624e5ea41
14 changed files with 434 additions and 28 deletions

View File

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

View File

@ -15,7 +15,7 @@ public interface ICollectionGenericObjects<T>
/// <summary>
/// Установка максимального количества элементов
/// </summary>
int SetMaxCount { set; }
int MaxCount { get; set; }
/// <summary>
/// Добавление объекта в коллекцию
@ -45,4 +45,16 @@ 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

@ -21,8 +21,9 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
public int Count => _collection.Count;
public int SetMaxCount
public int MaxCount
{
get => _maxCount;
set
{
if (value > 0)
@ -31,6 +32,9 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
}
}
}
public CollectionType GetCollectionType => CollectionType.List;
/// <summary>
/// Конструктор
/// </summary>
@ -66,4 +70,13 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
_collection.RemoveAt(position);
return temp;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < Count; i++)
{
yield return _collection[i];
}
}
}

View File

@ -14,8 +14,12 @@ 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)
@ -32,6 +36,8 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary>
/// Конструктор
/// </summary>
@ -115,4 +121,12 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
_collection[position] = null;
return obj;
}
public IEnumerable<T?> GetItems()
{
for (int i = 0; i < _collection.Length; i++)
{
yield return _collection[i];
}
}
}

View File

@ -1,13 +1,9 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Excavator.Drawnings;
using System.Text;
using System.Threading.Tasks;
namespace Excavator.CollectionGenericObjects;
public class StorageCollection<T>
where T : class
public class StorageCollection<T> where T : DrawningSimpleExcavator
{
/// <summary>
/// Словарь (хранилище) с коллекциями
@ -19,6 +15,21 @@ public class StorageCollection<T>
/// </summary>
public List<string> Keys => _storages.Keys.ToList();
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
/// <summary>
/// Конструктор
/// </summary>
@ -73,4 +84,139 @@ public class StorageCollection<T>
return null;
}
}
/// <summary>
/// Сохранение информации по автомобилям в хранилище в файл
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - сохранение прошло успешно, false - ошибка при сохранение данных</returns>
public bool SaveData(string filename)
{
if (_storages.Count == 0)
{
return false;
}
if (File.Exists(filename))
{
File.Delete(filename);
}
using (StreamWriter writer = new StreamWriter(filename))
{
writer.Write(_collectionKey);
foreach (KeyValuePair<string, ICollectionGenericObjects<T>> value in _storages)
{
StringBuilder sb = new();
sb.Append(Environment.NewLine);
// не сохраняем пустые коллекции
if (value.Value.Count == 0)
{
continue;
}
sb.Append(value.Key);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.GetCollectionType);
sb.Append(_separatorForKeyValue);
sb.Append(value.Value.MaxCount);
sb.Append(_separatorForKeyValue);
foreach (T? item in value.Value.GetItems())
{
string data = item?.GetDataForSave() ?? string.Empty;
if (string.IsNullOrEmpty(data))
{
continue;
}
sb.Append(data);
sb.Append(_separatorItems);
}
writer.Write(sb);
}
}
return true;
}
/// <summary>
/// Загрузка информации по автомобилям в хранилище из файла
/// </summary>
/// <param name="filename">Путь и имя файла</param>
/// <returns>true - загрузка прошла успешно, false - ошибка при загрузке данных</returns>
public bool LoadData(string filename)
{
if (!File.Exists(filename))
{
return false;
}
using (StreamReader fs = File.OpenText(filename))
{
string str = fs.ReadLine();
if (str == null || str.Length == 0)
{
return false;
}
if (!str.StartsWith(_collectionKey))
{
return false;
}
_storages.Clear();
string strs = "";
while ((strs = fs.ReadLine()) != null)
{
string[] record = strs.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?.CreateDrawningSimpleExcavator() is T excavator)
{
if (collection.Insert(excavator) == -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

@ -25,6 +25,14 @@ public class DrawningExcavator : DrawningSimpleExcavator
EntitySimpleExcavator = new EntityExcavator(speed, weight, bodyColor, additionalColor, supports, bucket);
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="airbus">Класс-сущность</param>
public DrawningExcavator(EntityExcavator excavator) : base(70, 80)
{
EntitySimpleExcavator = new EntityExcavator(excavator.Speed, excavator.Weight, excavator.BodyColor, excavator.AdditionalColor, excavator.Supports, excavator.Bucket);
}
public override void DrawTransport(Graphics g)
{

View File

@ -88,6 +88,16 @@ public class DrawningSimpleExcavator
}
/// <summary>
/// Конструктор
/// </summary>
/// <param name="airbus">Класс-сущность</param>
public DrawningSimpleExcavator(EntitySimpleExcavator simpleExcavator) : this()
{
EntitySimpleExcavator = new EntitySimpleExcavator(simpleExcavator.Speed, simpleExcavator.Weight, simpleExcavator.BodyColor);
}
/// <summary>
/// Конструктор для наследников
/// </summary>

View File

@ -0,0 +1,55 @@
using Excavator.Entities;
namespace Excavator.Drawnings;
/// <summary>
/// Расширение для класса EntityCar
/// </summary>
public static class ExtensionDrawningAirbus
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawningSimpleExcavator? CreateDrawningSimpleExcavator(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntitySimpleExcavator? excavator = EntityExcavator.CreateEntityExcavator(strs);
if (excavator != null)
{
return new DrawningExcavator((EntityExcavator)excavator);
}
excavator = EntitySimpleExcavator.CreateEntitySimpleExcavator(strs);
if (excavator != null)
{
return new DrawningSimpleExcavator(excavator);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningAirbus">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawningSimpleExcavator drawningSimpleExcavator)
{
string[]? array = drawningSimpleExcavator?.EntitySimpleExcavator?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@ -41,4 +41,30 @@ public class EntityExcavator : EntitySimpleExcavator
Supports = supports;
Bucket = bucket;
}
/// <summary>
/// Получение строк со значениями свойств объекта продвинутого класса-сущности
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new[] { nameof(EntityExcavator), Speed.ToString(), Weight.ToString(), BodyColor.Name,
AdditionalColor.Name, Supports.ToString(), Bucket.ToString() };
}
/// <summary>
/// Создание продвинутого объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntitySimpleExcavator? CreateEntityExcavator(string[] strs)
{
if (strs.Length != 7 || strs[0] != nameof(EntityExcavator))
{
return null;
}
return new EntityExcavator(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

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

View File

@ -46,10 +46,17 @@
buttonRemoveExcavator = new Button();
buttonRefresh = new Button();
pictureBox = new PictureBox();
menuStrip1 = new MenuStrip();
файлToolStripMenuItem = new ToolStripMenuItem();
SaveToolStripMenuItem = new ToolStripMenuItem();
LoadToolStripMenuItem = new ToolStripMenuItem();
openFileDialog = new OpenFileDialog();
saveFileDialog = new SaveFileDialog();
groupBoxTools.SuspendLayout();
panelStorage.SuspendLayout();
panelCompanyTools.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip1.SuspendLayout();
SuspendLayout();
//
// groupBoxTools
@ -60,9 +67,9 @@
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Controls.Add(panelCompanyTools);
groupBoxTools.Font = new Font("Microsoft Sans Serif", 8.25F, FontStyle.Regular, GraphicsUnit.Point);
groupBoxTools.Location = new Point(855, 1);
groupBoxTools.Location = new Point(855, 27);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(212, 634);
groupBoxTools.Size = new Size(212, 608);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
@ -185,7 +192,7 @@
//
// buttonGoToCheck
//
buttonGoToCheck.Location = new Point(6, 164);
buttonGoToCheck.Location = new Point(3, 148);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(191, 42);
buttonGoToCheck.TabIndex = 5;
@ -205,7 +212,7 @@
//
// maskedTextBoxPosition
//
maskedTextBoxPosition.Location = new Point(3, 91);
maskedTextBoxPosition.Location = new Point(3, 75);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(191, 20);
@ -213,7 +220,7 @@
//
// buttonRemoveExcavator
//
buttonRemoveExcavator.Location = new Point(6, 117);
buttonRemoveExcavator.Location = new Point(3, 101);
buttonRemoveExcavator.Name = "buttonRemoveExcavator";
buttonRemoveExcavator.Size = new Size(191, 41);
buttonRemoveExcavator.TabIndex = 4;
@ -223,7 +230,7 @@
//
// buttonRefresh
//
buttonRefresh.Location = new Point(6, 212);
buttonRefresh.Location = new Point(3, 196);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(191, 41);
buttonRefresh.TabIndex = 6;
@ -236,13 +243,54 @@
pictureBox.AccessibleRole = AccessibleRole.None;
pictureBox.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
pictureBox.BackgroundImageLayout = ImageLayout.None;
pictureBox.Location = new Point(0, 1);
pictureBox.Location = new Point(0, 27);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(855, 634);
pictureBox.Size = new Size(855, 608);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
pictureBox.Click += pictureBox_Click;
//
// menuStrip1
//
menuStrip1.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip1.Location = new Point(0, 0);
menuStrip1.Name = "menuStrip1";
menuStrip1.Size = new Size(1067, 24);
menuStrip1.TabIndex = 2;
menuStrip1.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;
//
// openFileDialog
//
openFileDialog.FileName = "openFileDialog1";
openFileDialog.Filter = "txt file | *.txt";
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// FormExcavatorCollection
//
AutoScaleDimensions = new SizeF(7F, 15F);
@ -250,6 +298,8 @@
ClientSize = new Size(1067, 635);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip1);
MainMenuStrip = menuStrip1;
Name = "FormExcavatorCollection";
Text = "Коллекция экскаваторов";
groupBoxTools.ResumeLayout(false);
@ -258,7 +308,10 @@
panelCompanyTools.ResumeLayout(false);
panelCompanyTools.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip1.ResumeLayout(false);
menuStrip1.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
#endregion
@ -281,5 +334,11 @@
private ListBox listBoxCollection;
private Button buttonCollectionDel;
private Button buttonCreateCompany;
private MenuStrip menuStrip1;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem SaveToolStripMenuItem;
private ToolStripMenuItem LoadToolStripMenuItem;
private OpenFileDialog openFileDialog;
private SaveFileDialog saveFileDialog;
}
}

View File

@ -227,4 +227,35 @@ public partial class FormExcavatorCollection : Form
panelCompanyTools.Enabled = true;
RerfreshListBoxItems();
}
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);
}
}
}
private void LoadToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
if (_storageCollection.LoadData(openFileDialog.FileName))
{
MessageBox.Show("Загрузка прошла успешно", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Не загрузилось", "Результат", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
RerfreshListBoxItems();
}
}

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="menuStrip1.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>132, 17</value>
</metadata>
<metadata name="saveFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>272, 17</value>
</metadata>
</root>

View File

@ -165,9 +165,9 @@
checkBoxSupports.AutoSize = true;
checkBoxSupports.Location = new Point(12, 134);
checkBoxSupports.Name = "checkBoxSupports";
checkBoxSupports.Size = new Size(106, 19);
checkBoxSupports.Size = new Size(114, 19);
checkBoxSupports.TabIndex = 7;
checkBoxSupports.Text = "Наличие опор";
checkBoxSupports.Text = "Наличие ковша";
checkBoxSupports.UseVisualStyleBackColor = true;
//
// checkBoxBucket
@ -175,9 +175,9 @@
checkBoxBucket.AutoSize = true;
checkBoxBucket.Location = new Point(12, 109);
checkBoxBucket.Name = "checkBoxBucket";
checkBoxBucket.Size = new Size(114, 19);
checkBoxBucket.Size = new Size(106, 19);
checkBoxBucket.TabIndex = 6;
checkBoxBucket.Text = "Наличие ковша";
checkBoxBucket.Text = "Наличие опор";
checkBoxBucket.UseVisualStyleBackColor = true;
//
// numericUpDownWeight