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

This commit is contained in:
sonyazubkova 2024-04-24 20:04:20 +04:00
parent 27f4bde173
commit b9afd42e2e
13 changed files with 455 additions and 31 deletions

View File

@ -47,14 +47,14 @@ public abstract class AbstractCompany
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_collection = collection;
_collection.SetMaxCount = GetMaxCount;
_collection.MaxCount = GetMaxCount;
}
/// <summary>
/// Перегрузка оператора сложения для класса
/// </summary>
/// <param name="company">Компания</param>
/// <param name="car">Добавляемый объект</param>
/// <param name="truck">Добавляемый объект</param>
/// <returns></returns>
public static int operator +(AbstractCompany company, DrawingTruck truck)
{

View File

@ -15,7 +15,7 @@ public interface ICollectionGenericObjects<T>
/// <summary>
/// Установка максимального количества элементов
/// </summary>
int SetMaxCount { set; }
int MaxCount { get; set; }
/// <summary>
/// Добавление объекта в коллекцию
@ -45,4 +45,15 @@ public interface ICollectionGenericObjects<T>
/// <returns>Объект</returns>
T? Get(int position);
/// <summary>
/// Получение типа коллекции
/// </summary>
CollectionType GetCollectionType { get; }
/// <summary>
/// Получение объектов коллекции по одному
/// </summary>
/// <returns>Поэлементый вывод элементов коллекции</returns>
IEnumerable<T?> GetItems();
}

View File

@ -18,7 +18,22 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
private int _maxCount;
public int Count => _collection.Count;
public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } }
public int MaxCount
{
get
{
return Count;
}
set
{
if (value > 0)
{
_maxCount = value;
}
}
}
public CollectionType GetCollectionType => CollectionType.List;
/// <summary>
/// Конструктор
@ -27,7 +42,7 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
{
_collection = new();
}
public T Get(int position)
public T? Get(int position)
{
// проверка позиции
if (position >= Count || position < 0)
@ -74,4 +89,12 @@ public class ListGenericObjects<T> : ICollectionGenericObjects<T>
return obj;
}
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)
@ -30,8 +34,10 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
}
}
}
public CollectionType GetCollectionType => CollectionType.Massive;
/// <summary>
/// Конструктор
@ -41,7 +47,6 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
_collection = Array.Empty<T?>();
}
public T? Get(int position)
{
// проверка позиции
@ -64,7 +69,6 @@ public class MassiveGenericObjects<T> : ICollectionGenericObjects<T>
}
return -1;
}
public int Insert(T obj, int position)
{
@ -115,4 +119,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,11 +1,14 @@
namespace ProjectGasolineTanker.CollectionGenericObjects;
using ProjectGasolineTanker.Drawings;
using System.Text;
namespace ProjectGasolineTanker.CollectionGenericObjects;
/// <summary>
/// Класс-хранилище коллекций
/// </summary>
/// <typeparam name="T"></typeparam>
public class StorageCollection<T>
where T : class
where T : DrawingTruck
{
/// <summary>
/// Словарь (хранилище) с коллекциями
@ -42,16 +45,16 @@ public class StorageCollection<T>
{
return;
}
else if (collectionType == CollectionType.Massive)
else if (collectionType == CollectionType.Massive)
{
_storages[name] = new MassiveGenericObjects<T>();
}
else if (collectionType == CollectionType.List)
else if (collectionType == CollectionType.List)
{
_storages[name] = new ListGenericObjects<T>();
}
}
/// <summary>
@ -60,7 +63,7 @@ public class StorageCollection<T>
/// <param name="name">Название коллекции</param>
public void DelCollection(string name)
{
// Прописать логику для удаления коллекции
// Логика для удаления коллекции
if (_storages.ContainsKey(name))
{
_storages.Remove(name);
@ -78,11 +81,158 @@ public class StorageCollection<T>
{
// логика получения объекта
if (_storages.ContainsKey(name))
{
{
return _storages[name];
}
return null;
}
}
/// <summary>
/// Ключевое слово, с которого должен начинаться файл
/// </summary>
private readonly string _collectionKey = "CollectionsStorage";
/// <summary>
/// Разделитель для записи ключа и значения элемента словаря
/// </summary>
private readonly string _separatorForKeyValue = "|";
/// <summary>
/// Разделитель для записей коллекции данных в файл
/// </summary>
private readonly string _separatorItems = ";";
/// <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?.CreateDrawingTruck() is T truck)
{
if (collection.Insert(truck) == -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

@ -20,7 +20,11 @@ public class DrawingGasolineTanker : DrawingTruck
{
EntityTruck = new EntityGasolineTanker(speed, weight, bodyColor, additionalColor, gasTank, signalBeacon);
}
public DrawingGasolineTanker(EntityGasolineTanker truck) : base(105,70)
{
EntityTruck = new EntityGasolineTanker(truck.Speed, truck.Weight, truck.BodyColor, truck.AdditionalColor, truck.GasTank, truck.SignalBeacon);
}
public override void DrawTransport(Graphics g)

View File

@ -49,12 +49,12 @@ public class DrawingTruck
public int? GetPosY => _startPosY;
/// <summary>
/// Ширина прорисовки воза(грузовика)
/// Ширина прорисовки грузовика
/// </summary>
public int GetWidth => _drawingTruckWidth;
/// <summary>
/// Высота прорисовки воза(грузовика)
/// Высота прорисовки грузовика
/// </summary>
public int GetHeight => _drawingTruckHeight;
@ -93,6 +93,11 @@ public class DrawingTruck
_drawingTruckHeight = drawingTruckHeight;
}
public DrawingTruck(EntityTruck truck) : this()
{
EntityTruck = new EntityTruck(truck.Speed, truck.Weight, truck.BodyColor);
}
/// <summary>
/// Установка границ поля
/// </summary>

View File

@ -0,0 +1,50 @@
namespace ProjectGasolineTanker.Drawings;
using ProjectGasolineTanker.Entities;
/// <summary>
/// Расширение для класса EntityTruck
/// </summary>
public static class ExtentionDrawingTruck
{
/// <summary>
/// Разделитель для записи информации по объекту в файл
/// </summary>
private static readonly string _separatorForObject = ":";
/// <summary>
/// Создание объекта из строки
/// </summary>
/// <param name="info">Строка с данными для создания объекта</param>
/// <returns>Объект</returns>
public static DrawingTruck? CreateDrawingTruck(this string info)
{
string[] strs = info.Split(_separatorForObject);
EntityTruck? truck = EntityGasolineTanker.CreateEntityGasolineTanker(strs);
if (truck != null)
{
return new DrawingGasolineTanker((EntityGasolineTanker)truck);
}
truck = EntityTruck.CreateEntityTruck(strs);
if (truck != null)
{
return new DrawingTruck(truck);
}
return null;
}
/// <summary>
/// Получение данных для сохранения в файл
/// </summary>
/// <param name="drawningTruck">Сохраняемый объект</param>
/// <returns>Строка с данными по объекту</returns>
public static string GetDataForSave(this DrawingTruck drawingTruck)
{
string[]? array = drawingTruck?.EntityTruck?.GetStringRepresentation();
if (array == null)
{
return string.Empty;
}
return string.Join(_separatorForObject, array);
}
}

View File

@ -34,4 +34,29 @@ public class EntityGasolineTanker : EntityTruck
SignalBeacon = signalBeacon;
}
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public override string[] GetStringRepresentation()
{
return new string[] {nameof(EntityGasolineTanker), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, GasTank.ToString(), SignalBeacon.ToString()};
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityGasolineTanker? CreateEntityGasolineTanker(string[] strs)
{
if (strs.Length != 7 || strs[0] != nameof(EntityGasolineTanker))
{
return null;
}
return new EntityGasolineTanker(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

@ -1,4 +1,6 @@
namespace ProjectGasolineTanker.Entities;
using System.Reflection.Metadata;
namespace ProjectGasolineTanker.Entities;
/// <summary>
/// Класс-сущность "Грузовик"
/// </summary>
@ -41,4 +43,27 @@ public class EntityTruck
BodyColor = bodyColor;
}
/// <summary>
/// Получение строк со значениями свойств объекта класса-сущности
/// </summary>
/// <returns></returns>
public virtual string[] GetStringRepresentation()
{
return new[] { nameof(EntityTruck), Speed.ToString(), Weight.ToString(), BodyColor.Name };
}
/// <summary>
/// Создание объекта из массива строк
/// </summary>
/// <param name="strs"></param>
/// <returns></returns>
public static EntityTruck? CreateEntityTruck(string[] strs)
{
if (strs.Length != 4 || strs[0] != nameof(EntityTruck))
{
return null;
}
return new EntityTruck(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();
groupBoxTools.SuspendLayout();
panelCompanyTools.SuspendLayout();
panelStorage.SuspendLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).BeginInit();
menuStrip.SuspendLayout();
SuspendLayout();
//
// groupBoxTools
@ -59,9 +66,9 @@
groupBoxTools.Controls.Add(panelStorage);
groupBoxTools.Controls.Add(comboBoxSelectorCompany);
groupBoxTools.Dock = DockStyle.Right;
groupBoxTools.Location = new Point(953, 0);
groupBoxTools.Location = new Point(941, 28);
groupBoxTools.Name = "groupBoxTools";
groupBoxTools.Size = new Size(241, 702);
groupBoxTools.Size = new Size(241, 802);
groupBoxTools.TabIndex = 0;
groupBoxTools.TabStop = false;
groupBoxTools.Text = "Инструменты";
@ -92,7 +99,7 @@
//
// buttonRefresh
//
buttonRefresh.Location = new Point(10, 273);
buttonRefresh.Location = new Point(10, 215);
buttonRefresh.Name = "buttonRefresh";
buttonRefresh.Size = new Size(222, 52);
buttonRefresh.TabIndex = 5;
@ -102,7 +109,7 @@
//
// maskedTextBoxPosition
//
maskedTextBoxPosition.Location = new Point(10, 124);
maskedTextBoxPosition.Location = new Point(9, 66);
maskedTextBoxPosition.Mask = "00";
maskedTextBoxPosition.Name = "maskedTextBoxPosition";
maskedTextBoxPosition.Size = new Size(222, 27);
@ -111,9 +118,9 @@
//
// buttonGoToCheck
//
buttonGoToCheck.Location = new Point(10, 215);
buttonGoToCheck.Location = new Point(13, 157);
buttonGoToCheck.Name = "buttonGoToCheck";
buttonGoToCheck.Size = new Size(225, 52);
buttonGoToCheck.Size = new Size(223, 52);
buttonGoToCheck.TabIndex = 4;
buttonGoToCheck.Text = "Передать на тесты";
buttonGoToCheck.UseVisualStyleBackColor = true;
@ -121,7 +128,7 @@
//
// buttonRemoveTruck
//
buttonRemoveTruck.Location = new Point(9, 157);
buttonRemoveTruck.Location = new Point(10, 99);
buttonRemoveTruck.Name = "buttonRemoveTruck";
buttonRemoveTruck.Size = new Size(226, 52);
buttonRemoveTruck.TabIndex = 3;
@ -237,19 +244,62 @@
//
pictureBox.Dock = DockStyle.Fill;
pictureBox.Enabled = false;
pictureBox.Location = new Point(0, 0);
pictureBox.Location = new Point(0, 28);
pictureBox.Name = "pictureBox";
pictureBox.Size = new Size(953, 702);
pictureBox.Size = new Size(941, 802);
pictureBox.TabIndex = 1;
pictureBox.TabStop = false;
//
// menuStrip
//
menuStrip.ImageScalingSize = new Size(20, 20);
menuStrip.Items.AddRange(new ToolStripItem[] { файлToolStripMenuItem });
menuStrip.Location = new Point(0, 0);
menuStrip.Name = "menuStrip";
menuStrip.Size = new Size(1182, 28);
menuStrip.TabIndex = 2;
menuStrip.Text = "menuStrip";
//
// файлToolStripMenuItem
//
файлToolStripMenuItem.DropDownItems.AddRange(new ToolStripItem[] { saveToolStripMenuItem, loadToolStripMenuItem });
файлToolStripMenuItem.Name = айлToolStripMenuItem";
файлToolStripMenuItem.Size = new Size(59, 24);
файлToolStripMenuItem.Text = "Файл";
//
// saveToolStripMenuItem
//
saveToolStripMenuItem.Name = "saveToolStripMenuItem";
saveToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.S;
saveToolStripMenuItem.Size = new Size(227, 26);
saveToolStripMenuItem.Text = "Сохранение";
saveToolStripMenuItem.Click += SaveToolStripMenuItem_Click;
//
// loadToolStripMenuItem
//
loadToolStripMenuItem.Name = "loadToolStripMenuItem";
loadToolStripMenuItem.ShortcutKeys = Keys.Control | Keys.L;
loadToolStripMenuItem.Size = new Size(227, 26);
loadToolStripMenuItem.Text = "Загрузка";
loadToolStripMenuItem.Click += LoadToolStripMenuItem_Click;
//
// saveFileDialog
//
saveFileDialog.Filter = "txt file | *.txt";
//
// openFileDialog
//
openFileDialog.Filter = "txt file | *.txt";
//
// FormTruckCollection
//
AutoScaleDimensions = new SizeF(8F, 20F);
AutoScaleMode = AutoScaleMode.Font;
ClientSize = new Size(1194, 702);
ClientSize = new Size(1182, 830);
Controls.Add(pictureBox);
Controls.Add(groupBoxTools);
Controls.Add(menuStrip);
MainMenuStrip = menuStrip;
Name = "FormTruckCollection";
Text = "Коллекция грузовиков";
groupBoxTools.ResumeLayout(false);
@ -258,7 +308,10 @@
panelStorage.ResumeLayout(false);
panelStorage.PerformLayout();
((System.ComponentModel.ISupportInitialize)pictureBox).EndInit();
menuStrip.ResumeLayout(false);
menuStrip.PerformLayout();
ResumeLayout(false);
PerformLayout();
}
@ -283,5 +336,11 @@
private Button buttonCreateCompany;
private Button buttonCollectionDel;
private Panel panelCompanyTools;
private MenuStrip menuStrip;
private ToolStripMenuItem файлToolStripMenuItem;
private ToolStripMenuItem saveToolStripMenuItem;
private ToolStripMenuItem loadToolStripMenuItem;
private SaveFileDialog saveFileDialog;
private OpenFileDialog openFileDialog;
}
}

View File

@ -1,5 +1,6 @@
using ProjectGasolineTanker.CollectionGenericObjects;
using ProjectGasolineTanker.Drawings;
using System.Windows.Forms;
namespace ProjectGasolineTanker;
@ -48,7 +49,7 @@ public partial class FormTruckCollection : Form
form.Show();
form.AddEvent(SetTruck);
}
/// <summary>
/// Добавление грузовика в коллекцию
/// </summary>
@ -240,5 +241,52 @@ public partial class FormTruckCollection : Form
panelCompanyTools.Enabled = true;
RerfreshListBoxItems();
}
/// <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(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,16 @@
<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>145, 17</value>
</metadata>
<metadata name="openFileDialog.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>310, 17</value>
</metadata>
<metadata name="$this.TrayHeight" type="System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>35</value>
</metadata>
</root>