From 6871b197bf72070d88ab5a95b78b4458b4ddd56d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9C=D0=B0=D0=BA=D1=81=D0=B8=D0=BC?= Date: Wed, 28 Aug 2024 21:10:45 +0400 Subject: [PATCH] h --- .../AbstractCompany.cs | 2 +- .../ICollectionGenericObjects.cs | 13 +- .../ListGenericObjects.cs | 22 ++- .../MassiveGenericObjects.cs | 15 +- .../StorageCollection.cs | 143 +++++++++++++++++- .../Drawnings/DrawningElectroTrain.cs | 7 + .../ProjertTrain/Drawnings/DrawningTrain.cs | 11 +- .../Drawnings/ExtentionDrawningTrain.cs | 50 ++++++ .../Entities/EntityElectroTrain.cs | 25 +++ .../ProjertTrain/Entities/EntityTrain.cs | 24 +++ 10 files changed, 305 insertions(+), 7 deletions(-) create mode 100644 ProjertTrain/ProjertTrain/Drawnings/ExtentionDrawningTrain.cs diff --git a/ProjertTrain/ProjertTrain/CollectionGenericObjects/AbstractCompany.cs b/ProjertTrain/ProjertTrain/CollectionGenericObjects/AbstractCompany.cs index 542b7ec..444a3fd 100644 --- a/ProjertTrain/ProjertTrain/CollectionGenericObjects/AbstractCompany.cs +++ b/ProjertTrain/ProjertTrain/CollectionGenericObjects/AbstractCompany.cs @@ -49,7 +49,7 @@ namespace ProjectTrain.CollectionGenericObjects _pictureWidth = picWidth; _pictureHeight = picHeight; _collection = collection; - _collection.SetMaxCount = GetMaxCount; + _collection.MaxCount = GetMaxCount; } /// diff --git a/ProjertTrain/ProjertTrain/CollectionGenericObjects/ICollectionGenericObjects.cs b/ProjertTrain/ProjertTrain/CollectionGenericObjects/ICollectionGenericObjects.cs index e0e56fe..25bf1b0 100644 --- a/ProjertTrain/ProjertTrain/CollectionGenericObjects/ICollectionGenericObjects.cs +++ b/ProjertTrain/ProjertTrain/CollectionGenericObjects/ICollectionGenericObjects.cs @@ -14,7 +14,7 @@ /// /// Установка максимального количества элементов /// - int SetMaxCount { set; } + int MaxCount { get; set; } /// /// Добавление объекта в коллекцию /// @@ -40,6 +40,17 @@ /// Позиция /// Объект T? Get(int position); + + /// + /// Получение типа коллекции + /// + CollectionType GetCollectionType { get; } + /// + /// Получение объектов коллекции по одному + /// + /// Поэлементый вывод элементов коллекции + IEnumerable GetItems(); + } } diff --git a/ProjertTrain/ProjertTrain/CollectionGenericObjects/ListGenericObjects.cs b/ProjertTrain/ProjertTrain/CollectionGenericObjects/ListGenericObjects.cs index d3aca01..dce6472 100644 --- a/ProjertTrain/ProjertTrain/CollectionGenericObjects/ListGenericObjects.cs +++ b/ProjertTrain/ProjertTrain/CollectionGenericObjects/ListGenericObjects.cs @@ -16,7 +16,20 @@ /// private int _maxCount; public int Count => _collection.Count; - public int SetMaxCount { set { if (value > 0) { _maxCount = value; } } } + public int MaxCount + { + get => _maxCount; + set + { + if (value > 0) + { + _maxCount = value; + } + } + } + + public CollectionType GetCollectionType => CollectionType.List; + /// /// Конструктор /// @@ -61,5 +74,12 @@ _collection.RemoveAt(position); return obj; } + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Count; ++i) + { + yield return _collection[i]; + } + } } } diff --git a/ProjertTrain/ProjertTrain/CollectionGenericObjects/MassiveGenericObjects.cs b/ProjertTrain/ProjertTrain/CollectionGenericObjects/MassiveGenericObjects.cs index 8e845db..9c459e8 100644 --- a/ProjertTrain/ProjertTrain/CollectionGenericObjects/MassiveGenericObjects.cs +++ b/ProjertTrain/ProjertTrain/CollectionGenericObjects/MassiveGenericObjects.cs @@ -15,8 +15,12 @@ namespace ProjectTrain.CollectionGenericObjects /// private T?[] _collection; public int Count => _collection.Length; - public int SetMaxCount + public int MaxCount { + get + { + return _collection.Length; + } set { if (value > 0) @@ -32,6 +36,7 @@ namespace ProjectTrain.CollectionGenericObjects } } } + public CollectionType GetCollectionType => CollectionType.Massive; /// /// Конструктор @@ -112,5 +117,13 @@ namespace ProjectTrain.CollectionGenericObjects _collection[position] = null; return obj; } + + public IEnumerable GetItems() + { + for (int i = 0; i < _collection.Length; ++i) + { + yield return _collection[i]; + } + } } } diff --git a/ProjertTrain/ProjertTrain/CollectionGenericObjects/StorageCollection.cs b/ProjertTrain/ProjertTrain/CollectionGenericObjects/StorageCollection.cs index 9323dee..8b9ce3d 100644 --- a/ProjertTrain/ProjertTrain/CollectionGenericObjects/StorageCollection.cs +++ b/ProjertTrain/ProjertTrain/CollectionGenericObjects/StorageCollection.cs @@ -1,10 +1,13 @@ -namespace ProjectTrain.CollectionGenericObjects +using ProjectTrain.Drawnings; +using System.Text; + +namespace ProjectTrain.CollectionGenericObjects { // Класс-хранилище коллекций /// /// public class StorageCollection - where T : class + where T : DrawningTrain { /// /// Словарь (хранилище) с коллекциями @@ -16,6 +19,21 @@ /// public List Keys => _storages.Keys.ToList(); + /// + /// Ключевое слово, с которого должен начинаться файл + /// + private readonly string _collectionKey = "CollectionsStorage"; + + /// + /// Разделитель для записи ключа и значения элемента словаря + /// + private readonly string _separatorForKeyValue = "|"; + + /// + /// Разделитель для записей коллекции данных в файл + /// + private readonly string _separatorItems = ";"; + /// /// Конструктор /// @@ -69,5 +87,126 @@ return null; } } + /// + /// Сохранение информации по автомобилям в хранилище в файл + /// + /// Путь и имя файла + /// true - сохранение прошло успешно, false - ошибка при сохранении данных + 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> 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; + } + + /// + /// Загрузка информации по автомобилям в хранилище из файла + /// + /// Путь и имя файла + /// true - загрузка прошла успешно, false - ошибка при загрузке данных + 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? collection = StorageCollection.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?.CreateDrawningTrain() is T train) + { + if (collection.Insert(train) == -1) + { + return false; + } + } + } + _storages.Add(record[0], collection); + } + return true; + + } + } + + /// + /// Создание коллекции по типу + /// + /// + /// + private static ICollectionGenericObjects? CreateCollection(CollectionType collectionType) + { + return collectionType switch + { + CollectionType.Massive => new MassiveGenericObjects(), + CollectionType.List => new ListGenericObjects(), + _ => null, + }; + } + } } diff --git a/ProjertTrain/ProjertTrain/Drawnings/DrawningElectroTrain.cs b/ProjertTrain/ProjertTrain/Drawnings/DrawningElectroTrain.cs index 7d70a21..1670206 100644 --- a/ProjertTrain/ProjertTrain/Drawnings/DrawningElectroTrain.cs +++ b/ProjertTrain/ProjertTrain/Drawnings/DrawningElectroTrain.cs @@ -22,6 +22,13 @@ namespace ProjectTrain.Drawnings { EntityTrain = new EntityElectroTrain(speed, weight, bodyColor, additionalColor, horns, electro, headlight); } + public DrawningElectroTrain(EntityTrain entityTrain) + { + if (entityTrain != null) + { + EntityTrain = entityTrain; + } + } public override void DrawTransport(Graphics g) { diff --git a/ProjertTrain/ProjertTrain/Drawnings/DrawningTrain.cs b/ProjertTrain/ProjertTrain/Drawnings/DrawningTrain.cs index d8963ce..2e8957f 100644 --- a/ProjertTrain/ProjertTrain/Drawnings/DrawningTrain.cs +++ b/ProjertTrain/ProjertTrain/Drawnings/DrawningTrain.cs @@ -58,7 +58,7 @@ public class DrawningTrain /// /// Пустой онструктор /// - private DrawningTrain() + public DrawningTrain() { _pictureWidth = null; _pictureHeight = null; @@ -87,6 +87,15 @@ public class DrawningTrain _pictureHeight = drawningCarHeight; } + /// + /// конструктор + /// + /// + public DrawningTrain(EntityTrain entityTrain) + { + EntityTrain = entityTrain; + } + /// /// Установка границ поля /// diff --git a/ProjertTrain/ProjertTrain/Drawnings/ExtentionDrawningTrain.cs b/ProjertTrain/ProjertTrain/Drawnings/ExtentionDrawningTrain.cs new file mode 100644 index 0000000..2cc0f17 --- /dev/null +++ b/ProjertTrain/ProjertTrain/Drawnings/ExtentionDrawningTrain.cs @@ -0,0 +1,50 @@ +using ProjectTrain.Entities; + +namespace ProjectTrain.Drawnings +{ + public static class ExtentionDrawningTrain + { + /// + /// Разделитель для записи информации по объекту в файл + /// + private static readonly string _separatorForObject = ":"; + + /// + /// Создание объекта из строки + /// + /// Строка с данными для создания объекта + /// Объект + public static DrawningTrain? CreateDrawningTrain(this string info) + { + string[] strs = info.Split(_separatorForObject); + EntityTrain? train = EntityElectroTrain.CreateEntityElectroTrain(strs); + if (train != null) + { + return new DrawningElectroTrain(train); + } + + train = EntityTrain.CreateEntityTrain(strs); + if (train != null) + { + return new DrawningTrain(train); + } + return null; + } + + /// + /// Получение данных для сохранения в файл + /// + /// Сохраняемый объект + /// Строка с данными по объекту + public static string GetDataForSave(this DrawningTrain drawningTrain) + { + string[]? array = drawningTrain?.EntityTrain?.GetStringRepresentation(); + if (array == null) + { + return string.Empty; + } + return string.Join(_separatorForObject, array); + } + + } +} diff --git a/ProjertTrain/ProjertTrain/Entities/EntityElectroTrain.cs b/ProjertTrain/ProjertTrain/Entities/EntityElectroTrain.cs index 1640e41..c573720 100644 --- a/ProjertTrain/ProjertTrain/Entities/EntityElectroTrain.cs +++ b/ProjertTrain/ProjertTrain/Entities/EntityElectroTrain.cs @@ -34,5 +34,30 @@ Electro = electro; Headlight = headlight; } + + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public override string[] GetStringRepresentation() + { + return new[] { nameof(EntityTrain), Speed.ToString(), Weight.ToString(), BodyColor.Name, AdditionalColor.Name, + Horns.ToString(), Electro.ToString(), Headlight.ToString() }; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityTrain? CreateEntityElectroTrain(string[] strs) + { + if (strs.Length != 8 || strs[0] != nameof(EntityTrain)) + { + return null; + } + return new EntityElectroTrain(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3]), Color.FromName(strs[4]), + Convert.ToBoolean(strs[5]), Convert.ToBoolean(strs[6]), Convert.ToBoolean(strs[7])); + } } } diff --git a/ProjertTrain/ProjertTrain/Entities/EntityTrain.cs b/ProjertTrain/ProjertTrain/Entities/EntityTrain.cs index 82be469..6fa0fe2 100644 --- a/ProjertTrain/ProjertTrain/Entities/EntityTrain.cs +++ b/ProjertTrain/ProjertTrain/Entities/EntityTrain.cs @@ -38,4 +38,28 @@ public class EntityTrain Weight = weight; BodyColor = bodyColor; } + + /// + /// Получение строк со значениями свойств объекта класса-сущности + /// + /// + public virtual string[] GetStringRepresentation() + { + return new[] { nameof(EntityTrain), Speed.ToString(), Weight.ToString(), BodyColor.Name }; + } + + /// + /// Создание объекта из массива строк + /// + /// + /// + public static EntityTrain? CreateEntityTrain(string[] strs) + { + if (strs.Length != 4 || strs[0] != nameof(EntityTrain)) + { + return null; + } + + return new EntityTrain(Convert.ToInt32(strs[1]), Convert.ToDouble(strs[2]), Color.FromName(strs[3])); + } }