Created
May 22, 2016 03:48
-
-
Save nuitsjp/717b48efa4e52776553221567f9ce578 to your computer and use it in GitHub Desktop.
This file contains 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; | |
namespace SingletonSample | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
SingletonClass.Instance.Initialize(); | |
Console.WriteLine(SingletonClass.Instance.Value); | |
Console.WriteLine(SingletonClass.Instance.Value); // どこからも同じインスタンスを参照できる | |
SingletonClass.Instance.Value = "foo"; | |
Console.WriteLine(SingletonClass.Instance.Value); | |
} | |
} | |
/// <summary> | |
/// システム全体から一つしかインスタンスが存在しないことを保証するクラス。 | |
/// 「シングルトン=たった一つの」を保証するデザインパターン | |
/// </summary> | |
public class SingletonClass | |
{ | |
/// <summary> | |
/// たった一つのインスタンス | |
/// </summary> | |
public static SingletonClass Instance { get; } = new SingletonClass(); | |
public string Value { get; set; } | |
/// <summary> | |
/// インスタンスが一つきりであることを保証するためコンストラクタは隠ぺいする | |
/// </summary> | |
private SingletonClass() | |
{ | |
} | |
/// <summary> | |
/// なんか初期化メソッド | |
/// </summary> | |
public void Initialize() | |
{ | |
Value = "hoge"; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment