PowerToys/Wox.Infrastructure/Storage/BaseStorage.cs

93 lines
2.3 KiB
C#
Raw Normal View History

2014-03-23 16:17:41 +08:00
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices.ComTypes;
2014-03-23 16:17:41 +08:00
using System.Text;
using Newtonsoft.Json;
namespace Wox.Infrastructure.Storage
{
[Serializable]
2014-12-29 21:55:27 +08:00
public abstract class BaseStorage<T> : IStorage where T : class,IStorage, new()
2014-03-23 16:17:41 +08:00
{
protected abstract string ConfigFolder { get; }
protected string ConfigPath
{
get
{
2014-12-29 21:55:27 +08:00
return Path.Combine(ConfigFolder, ConfigName + FileSuffix);
}
}
2014-12-29 21:55:27 +08:00
protected abstract string FileSuffix { get; }
protected abstract string ConfigName { get; }
2014-03-23 16:17:41 +08:00
private static object locker = new object();
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
{
if (!File.Exists(ConfigPath))
2014-03-23 16:17:41 +08:00
{
2014-12-29 21:55:27 +08:00
if (!Directory.Exists(ConfigFolder))
2014-03-23 16:17:41 +08:00
{
2014-12-29 21:55:27 +08:00
Directory.CreateDirectory(ConfigFolder);
2014-03-23 16:17:41 +08:00
}
File.Create(ConfigPath).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
}
}
}
}