PowerToys/Wox.Infrastructure/Storage/BaseStorage.cs

93 lines
2.4 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.Runtime.InteropServices.ComTypes;
2014-03-23 16:17:41 +08:00
using System.Text;
using System.Windows.Forms;
using Newtonsoft.Json;
namespace Wox.Infrastructure.Storage
{
[Serializable]
public abstract class BaseStorage<T> : IStorage where T : class,IStorage,new()
2014-03-23 16:17:41 +08:00
{
private readonly string configFolder = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Config");
protected string ConfigPath
{
get
{
return Path.Combine(configFolder, ConfigName + FileSuffix);
}
}
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 serializedObject;
}
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
{
if (!Directory.Exists(configFolder))
2014-03-23 16:17:41 +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
}
}
}
}