wonderfl用Singletonクラスサンプル

by Hiiragi
wonderfl用Singletonクラスサンプル
@author Hiiragi

自分的にSingletonは

「どこからでもアクセスできる設定保存クラス」

な使い方が多いので、それをwonderfl用に作ってみました。
単なる備忘録です。
♥0 | Line 57 | Modified 2010-03-01 15:41:57 | MIT License
play

ActionScript3 source code

/**
 * Copyright Hiiragi ( http://wonderfl.net/user/Hiiragi )
 * MIT License ( http://www.opensource.org/licenses/mit-license.php )
 * Downloaded from: http://wonderfl.net/c/s18B
 */

package  
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	
	/**
	 * wonderfl用Singletonクラスサンプル
	 * @author Hiiragi
	 * 
	 * 自分的にSingletonは
	 * 
	 * 「どこからでもアクセスできる設定保存クラス」
	 * 
	 * な使い方が多いので、それをwonderfl用に作ってみました。
	 * 単なる備忘録です。
	 * 
	 */
	[SWF(width = 465, height = 465, frameRate = 30, backgroundColor = 0xFFFFFF)]
	public class SingletonTest extends Sprite
	{
		private var _tf:TextField;
		
		public function SingletonTest() 
		{
			_tf = new TextField();
			_tf.autoSize = TextFieldAutoSize.LEFT;
			this.addChild(_tf);
			
			this.addEventListener(Event.ENTER_FRAME, onEnterFrameHandler);
		}
		
		private function onEnterFrameHandler(e:Event):void 
		{
			//GlobalSettingクラスに保存されている数値にインクリメントしていく
			GlobalSetting.getInstance().hoge++;
			_tf.appendText(GlobalSetting.getInstance().hoge.toString() + "\n");
			
			//単なる位置修正
			positionFix();
		}
		
		private function positionFix():void
		{
			if (_tf.height > this.stage.stageHeight)
			{
				_tf.y = this.stage.stageHeight - _tf.height;
			}
		}
		
	}

}

//wonderfl用Singletonクラス
class GlobalSetting
{
	private static var _instance:GlobalSetting;
	private static var _createdFlag:Boolean = false;
	
	//Property
	private var _hoge:int = 0;
	
	public function GlobalSetting() 
	{
		//getInstance()前にnewしようとしても、_createdFlagがfalseだからエラー。
		//getInstance()後にnewしようとしても、_instanceがnullじゃないからエラー。
		//というわけで、getInstance()以外ではnew出来ない仕様。
		if (_instance != null || !_createdFlag)	throw new Error("This class is Singleton.");
	}
	
	public static function getInstance():GlobalSetting 
	{
		if (_instance == null)
		{
			_createdFlag = true;
			//_instanceはnullだし、_createFlagはtrueだから、コンストラクタでエラーが出ない。
			_instance = new GlobalSetting();
		}
		return _instance;
	}
	
	// getter / setter -------------------------------------------------------------------
	public function get hoge():int { return _hoge; }
	
	public function set hoge(value:int):void 
	{
		_hoge = value;
	}
}