5
3

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 3 years have passed since last update.

シングルトンパターンとは

Last updated at Posted at 2022-04-01

シングルトンとは

OOPの代表的なデザインパターンの一つで、

  • インスタンスが一つしか作られないようなクラスを作成する
  • その唯一のインスタンスに対するグローバルなアクセスポイントを提供する

というもの。

例えばHumanっていうクラスがあったとして、それに対して$takeshi$hanakoといったインスタンスを複数作るのではなく、$humanっていうインスタンスを一つだけ作らせるようすr

シングルトンのメリット

なんでそんなことをするのかというと、以下のようなメリットがあるため

  • アプリケーションのウィンドウのように一つしか存在してはいけないものが複数生成されるのを防ぐことができる
  • インスタンスが一つしか作られないので、メモリ消費量を節約できる(ロガーなど全アプリケーションで使用するがいちいちインスタンス化する必要が無いもの)
  • 設定値などを一つのインスタンスのプロパティに貯めておける(ランタイム中はその設定値をどこからでも利用できる)
  • 複数スレッドを使用するアプリケーションで複数スレッドの処理を一元管理できる

シングルトンの埋め込み方法

一般的には以下の方法で埋め込まれる

  • インスタンスを保持するプライベート変数を定義
  • ファクトリーメソッド(下記コードのgetInstance())を作成し、上記のプライベート変数にインスタンスがセットされていなければ新しいインスタンスを作成し、存在する場合はそのインスタンスを返却する
class Singleton {
	private static Singleton instance;

	private Singleton() {
		...
	}
	
	public static synchronized Singleton getInstance(){

		if (instance == null)
			instance = new Singleton();

		return instance;
	}
	
	...
	
	public void doSomething()
	{
		...
	}
}
// 呼び出し例
Singleton.getInstance().doSomething();

参考

5
3
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
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?