80
78

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C# で シングルトンパターン

Last updated at Posted at 2012-12-26

C# で シングルトンパターン

時々使うけど、すぐ忘れるのでメモ。

デザインパターンのうち、Singletonパターン(1つしかインスタンスを生成しない)

コンストラクタのスコープを private に変更し、
GetInstance()メソッドでインスタンスを取得するようにするのが肝です。

sample_singleton.cs
// Singletonパターン
public sealed class SingletonClass
{
	private static SingletonClass _singleInstance = new SingletonClass();

	public static SingletonClass GetInstance()
	{
		return _singleInstance;
	}

	private SingletonClass()
	{
	    //TODO: initialization
	}
}

参考

追記

SharpDevelopなら、新規作成→(中略)→シングルトンクラス を選択すると、
一瞬で以下のように生成してくれるじゃないですかーやだ恥ずかしー(赤面)

SamplaSingletonClass.cs
using System;

namespace SampleLog4Net
{
	/// <summary>
	/// Description of ClassNullLogger.
	/// </summary>
	public sealed class ClassNullLogger
	{
		private static ClassNullLogger instance = new ClassNullLogger();
		
		public static ClassNullLogger Instance {
			get {
				return instance;
			}
		}
		
		private ClassNullLogger()
		{
		}
	}
}
80
78
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
80
78

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?