Created
May 22, 2016 08:34
-
-
Save nuitsjp/aeb65aa96b3ede7b0e4b54a772957d4b to your computer and use it in GitHub Desktop.
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) | |
{ | |
Run(); | |
Console.ReadLine(); | |
} | |
private static async void Run() | |
{ | |
var instance = await SingletonClass.GetInstance(); | |
Console.WriteLine(await instance.GetValue()); | |
} | |
} | |
/// <summary> | |
/// システム全体から一つしかインスタンスが存在しないことを保証するクラス。 | |
/// 「シングルトン=たった一つの」を保証するデザインパターン | |
/// </summary> | |
public class SingletonClass | |
{ | |
private static bool isInitialized = false; | |
/// <summary> | |
/// たった一つのインスタンス | |
/// </summary> | |
private static SingletonClass instance = new SingletonClass(); | |
private string value; | |
/// <summary> | |
/// インスタンスが一つきりであることを保証するためコンストラクタは隠ぺいする | |
/// </summary> | |
private SingletonClass() | |
{ | |
} | |
/// <summary> | |
/// 唯一のインスタンスを取得する | |
/// </summary> | |
/// <returns></returns> | |
public static Task<SingletonClass> GetInstance() | |
{ | |
return Task.Run(() => | |
{ | |
// 初期化済みか判定する | |
if(!isInitialized) | |
{ | |
// シングルトンインスタンスをロックし、その後改めて初期化状態の再チェックを行う | |
// ダブル・チェック・ロッキングパターン | |
lock (instance) | |
{ | |
if (!isInitialized) | |
instance.Initialize(); | |
} | |
} | |
return instance; | |
}); | |
} | |
/// <summary> | |
/// なんか初期化メソッド | |
/// </summary> | |
public void Initialize() | |
{ | |
// ここでjson読んでデシリアライズ処理すると良いかも。 | |
// 重たい処理を想定 | |
value = "hoge"; | |
} | |
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