java設計モード:Singletonモード

808 ワード

Singletonモードはjavaで最も多く使われている設計モードである。制御する個数に使用し、余分な実例化や修正を防ぐ。オブジェクトが一つしか存在しない場合、動作は有効です。
1、コンストラクタの私有化、他のクラスはオブジェクトを具体化できません。
2、私有化を引用し、他の変更はない。
3、公有の静的方法でオブジェクトを一意に取得する
最初の実装:
class AmericanPresident
{
	private static final AmericanPresident thePresident = new AmericanPresident();
	
	private AmericanPresident() {}
	
	public static AmericanPresident getPresident()
	{
		return thePresident;
	}
}
第二の実現:
class AmericanPresident
{
	private static AmericanPresident thePresident ;
	
	private AmericanPresident() {}
	
	public static AmericanPresident getPresident()
	{
		if (thePresident == null) thePresident = new AmericanPresident();
		
		return thePresident;
	}
}
java標準ライブラリでsingletonモードを使用しているのは、java.lang.Runtime()である。