Created
May 22, 2016 11:34
-
-
Save nuitsjp/69bde4c2676372288f0664a9b4fec0e4 to your computer and use it in GitHub Desktop.
初期化処理の重たいシングルトンクラスのLazyを使った実装例
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Threading.Tasks; | |
namespace SingletonSample | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
Task.Run(async () => | |
{ | |
var instance = await SingletonClass.GetInstance(); | |
Console.WriteLine(await instance.GetValue()); | |
}).Wait(); | |
} | |
} | |
/// <summary> | |
/// システム全体から一つしかインスタンスが存在しないことを保証するクラス。 | |
/// 「シングルトン=たった一つの」を保証するデザインパターン | |
/// </summary> | |
public class SingletonClass | |
{ | |
/// <summary> | |
/// たった一つのインスタンス | |
/// </summary> | |
private static Lazy<SingletonClass> instance = new Lazy<SingletonClass>(() => new SingletonClass(), true); | |
/// <summary> | |
/// 取得するのが重たいオブジェクト | |
/// </summary> | |
private string value; | |
/// <summary> | |
/// インスタンスが一つきりであることを保証するためコンストラクタは隠ぺいする | |
/// </summary> | |
private SingletonClass() | |
{ | |
// ここでjson読んでデシリアライズ処理する遅い処理。 | |
this.value = "hoge"; | |
} | |
/// <summary> | |
/// 唯一のインスタンスを取得する | |
/// </summary> | |
/// <returns></returns> | |
public static Task<SingletonClass> GetInstance() | |
{ | |
return Task.Run(() => | |
{ | |
return instance.Value; | |
}); | |
} | |
/// <summary> | |
/// | |
/// </summary> | |
/// <returns></returns> | |
public Task<string> GetValue() | |
{ | |
return Task.Run(() => | |
{ | |
return value; | |
}); | |
} | |
public Task SetValue(string value) | |
{ | |
return Task.Run(() => | |
{ | |
this.value = value; | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment