18
18

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.

いろんなシングルトンパターン

18
Last updated at Posted at 2012-02-08

サンプルコード

どの書き方が好みですか?
せるさんにネーミングが変と言われて、最初は気にしなかったけどちょっと気になってきたのでなおしたw

Test.as
package  
{
	import flash.display.Sprite;
	import hoge.moja.NewSingleton;
	import hoge.moja.OldSingleton;
	import hoge.moja.OldSingleton2;
	
	public class Test extends Sprite 
	{
		public function Test() 
		{
			OldSingleton.getInstance().test();
			OldSingleton2.getInstance().test();
			NewSingleton.test();
		}
	}
}

よく使われるシングルトンパターン。

問題としては getSingleton() を呼ぶ前は new できてしまう。

hoge.moja.OldSingleton.as
package hoge.moja 
{
	public class OldSingleton 
	{
		private static var _instance: OldSingleton;
		
		public function OldSingleton() 
		{
			if (_instance) 
				throw new Error("シングルトンインスタンスは new できません");
		}
		
		public function test(): void
		{
			trace("old singleton");
		}
		
		public static function getInstance(): OldSingleton
		{
			return _instance||= new OldSingleton();
		}
	}
}

よく使われるシングルトンパターンを改良したもの。

OldSingletonImpl は他のクラスから参照できないので他のクラスが new できない。

hoge.moja.OldSingleton2.as
package hoge.moja 
{
	public class OldSingleton2 
	{
		private static var _instance: OldSingleton2;
		
		public function OldSingleton2(impl: OldSingletonImpl) { }
		
		public function test(): void
		{
			trace("old singleton 2");
		}
		
		public static function getInstance(): OldSingleton2
		{
			return _instance||= new OldSingleton2(new OldSingletonImpl());
		}
	}
}
class OldSingletonImpl
{
	function OldSingletonImpl() { };
}

新しいシングルトンパターン。

簡単に書ける。

hoge.moja.NewSingleton.as
package hoge.moja 
{
	public const NewSingleton: NewSingletonClass = new NewSingletonClass();
}
class NewSingletonClass
{
	function NewSingletonClass() { }
	
	public function test(): void
	{
		trace("new singleton");
	}
}
18
18
3

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
18
18

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?