Skip to content

Instantly share code, notes, and snippets.

@nk0t
Created March 8, 2013 13:59
Show Gist options
  • Save nk0t/5116603 to your computer and use it in GitHub Desktop.
Save nk0t/5116603 to your computer and use it in GitHub Desktop.
設定管理クラス的な何か
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestApplication.Core.Configuration
{
public sealed class SettingManager
{
#region Singleton
private static Lazy<SettingManager> _instance = new Lazy<SettingManager>(() => { return new SettingManager(); }, true);
public static SettingManager Instance
{
get
{
return _instance.Value;
}
}
#endregion
private SettingManager()
{
_settingsDictionary = new Dictionary<Type, SettingBase>();
}
private Dictionary<Type, SettingBase> _settingsDictionary;
public Dictionary<Type, SettingBase> SettingsDictionary
{
get { return _settingsDictionary; }
set { _settingsDictionary = value; }
}
public static void AddSetting(SettingBase setting)
{
if (!Instance.SettingsDictionary.ContainsKey(setting.GetType()))
{
Instance.SettingsDictionary.Add(setting.GetType(), setting);
}
}
public static void LoadAllSettings()
{
foreach (var kv in Instance.SettingsDictionary.ToArray())
{
try
{
Instance.SettingsDictionary[kv.Key] = Serializer.LoadXML(kv.Value.SettingFilePath, true, kv.Value);
}
catch (FileNotFoundException) { }
}
}
public static void SaveAllSettings()
{
foreach (var kv in Instance.SettingsDictionary)
{
SaveSetiings(kv.Value);
}
}
private static void SaveSetiings(SettingBase setting)
{
var temp = Path.GetTempFileName();
try
{
Serializer.SaveXML(temp, setting);
File.Delete(setting.SettingFilePath);
File.Move(temp, setting.SettingFilePath);
}
catch (Exception e)
{
throw e;
}
}
public static T GetSetting<T>() where T : SettingBase
{
if (Instance.SettingsDictionary.ContainsKey(typeof(T)))
{
return (T)Instance.SettingsDictionary[typeof(T)];
}
return default(T);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment