C# Tips


Singletonパターン


もっとも有名なデザインパターンのひとつにSingletonがあります。
これは、マルチスレッド、ネットワーク環境において非常に重要な
デザインパターンです。
キーポイントはコンストラクタをprivateにすることです。
基本的なSingletonクラスをC#で書いて見ましょう。
あとは、このクラスを拡張する際にlockを用いて必要な排他制御をしていきましょう。
sealed class Singleton
{
	private static int numberOfReference;
	private string data;

	private static Singleton instance = new Singleton();

	// private constructor
	private Singleton()
	{
		numberOfReference = 0;
		data = "This is Singleton Class.";
	}

	public static Singleton GetInstance()
	{
		numberOfReference++;
		return instance;
	}            

	public static int Reference
	{
		get
		{
			return numberOfReference;
		}
	}  

	public string Data
	{
		get
		{
			return data;
		}
		set
		{
			data = value;
		}
	}
}  


目次に戻る
Copyright(c) 2008 WoodenSoldier Software