PowerToys/Wox.Infrastructure/Storage/BaseStorage.cs

82 lines
2.1 KiB
C#
Raw Normal View History

2014-03-23 16:17:41 +08:00
using System;
using System.IO;
namespace Wox.Infrastructure.Storage
{
[Serializable]
2016-01-07 10:31:17 +08:00
public abstract class BaseStorage<T> : IStorage where T : class, IStorage, new()
2014-03-23 16:17:41 +08:00
{
2016-01-07 10:31:17 +08:00
protected string DirectoryPath { get; } = Path.Combine(WoxDirectroy.Executable, "Config");
2016-01-07 10:31:17 +08:00
protected string FilePath => Path.Combine(DirectoryPath, FileName + FileSuffix);
2014-12-29 21:55:27 +08:00
protected abstract string FileSuffix { get; }
2016-01-07 10:31:17 +08:00
protected abstract string FileName { get; }
2014-03-23 16:17:41 +08:00
private static object locker = new object();
2016-01-07 10:31:17 +08:00
protected static T serializedObject;
2014-03-23 16:17:41 +08:00
public event Action<T> AfterLoad;
protected virtual void OnAfterLoad(T obj)
{
Action<T> handler = AfterLoad;
if (handler != null) handler(obj);
}
2014-03-23 16:17:41 +08:00
public static T Instance
{
get
{
if (serializedObject == null)
2014-03-23 16:17:41 +08:00
{
lock (locker)
{
if (serializedObject == null)
2014-03-23 16:17:41 +08:00
{
serializedObject = new T();
serializedObject.Load();
2014-03-23 16:17:41 +08:00
}
}
}
return serializedObject;
2014-03-23 16:17:41 +08:00
}
}
/// <summary>
/// if loading storage failed, we will try to load default
/// </summary>
/// <returns></returns>
protected virtual T LoadDefault()
{
return new T();
}
2014-03-23 18:14:46 +08:00
protected abstract void LoadInternal();
protected abstract void SaveInternal();
public void Load()
2014-03-23 16:17:41 +08:00
{
2016-01-07 10:31:17 +08:00
if (!File.Exists(FilePath))
2014-03-23 16:17:41 +08:00
{
2016-01-07 10:31:17 +08:00
if (!Directory.Exists(DirectoryPath))
2014-03-23 16:17:41 +08:00
{
2016-01-07 10:31:17 +08:00
Directory.CreateDirectory(DirectoryPath);
2014-03-23 16:17:41 +08:00
}
2016-01-07 10:31:17 +08:00
File.Create(FilePath).Close();
2014-03-23 16:17:41 +08:00
}
LoadInternal();
OnAfterLoad(serializedObject);
2014-03-23 16:17:41 +08:00
}
public void Save()
{
lock (locker)
{
SaveInternal();
2014-03-23 16:17:41 +08:00
}
}
}
}