<?xml version="1.0" encoding="UTF-8"?>
<!-- generator="wordpress/2.3.3" -->
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	>

<channel>
	<title>{ P I X E L W E L D E R S } &#187; Design Patterns</title>
	<link>http://pixelwelders.com/blog</link>
	<description>Flash + Flex + Game Dev + Grammar?</description>
	<pubDate>Tue, 04 Nov 2008 14:18:05 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.3.3</generator>
	<language>en</language>
			<item>
		<title>The Art and Beauty of Singletons</title>
		<link>http://pixelwelders.com/blog/best-practices/2008/art-and-beauty-of-singletons-in-as3/</link>
		<comments>http://pixelwelders.com/blog/best-practices/2008/art-and-beauty-of-singletons-in-as3/#comments</comments>
		<pubDate>Mon, 14 Apr 2008 09:02:27 +0000</pubDate>
		<dc:creator>Zack Jordan</dc:creator>
		
		<category><![CDATA[ActionScript 3.0]]></category>

		<category><![CDATA[Best Practices]]></category>

		<category><![CDATA[Design Patterns]]></category>

		<category><![CDATA[Actionscript]]></category>

		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://pixelwelders.com/blog/best-practices/2008/art-and-beauty-of-singletons-in-as3/</guid>
		<description><![CDATA[A) In poker, a card that is the only one of its rank.
B) In animal husbandry, the sole surviving offspring of a litter.
C) In astrology, a single planet alone in a hemisphere (or some crap like that).
D) In mathematics, a set with only one member.
E) In England, a small village about 7 miles north of Chichester in West Sussex.

What do all these things have in common?]]></description>
			<content:encoded><![CDATA[<h3>What is a Singleton?</h3>
<p>A) In poker, a card that is the only one of its rank.<br />
B) In animal husbandry, the sole surviving offspring of a litter.<br />
C) In astrology, a single planet alone in a hemisphere (or some crap like that).<br />
D) In mathematics, a set with only one member.<br />
E) In England, a small village about 7 miles north of Chichester in West Sussex.</p>
<p><img src='http://pixelwelders.com/blog/wp-content/uploads/2008/04/singleton_cat_350.jpg' alt='A cute yet tragic Singleton' style="float:left; margin:0.5em 1.5em 1.5em 0em;" /></p>
<p>All of these things share a trait, and that trait is that each is the only one of its kind.  If two kittens survive from a litter, neither one is a singleton.  If a set has more than one number, it is not a singleton.  In works the same way in object-oriented programming; a Singleton is a class that allows only one instance of itself; if there are more than one, that class cannot be a Singleton.</p>
<p>So why would one want a class that only allows one instance of itself?  I can think of many applications.  A ScoreKeeper class for your game, perhaps, or a Countdown class that keeps track of how much time you have to complete a level.  In <a href=”http://os-wars.com” target=”_blank”>OS Wars</a> I use a Singleton to keep track of all building resources currently in the game.  There’s another one that keeps track of all the units on the battlefield.  In fact, the Battlefield itself is a Singleton, because there’s no reason I would ever need more than one.</p>
<p>Another great thing about a Singleton is that, because there is only one, it’s very easy to get to.  With a normal object, you have to worry about passing it around to the various classes that might need it.  With a Singleton, that’s not necessary.  All you need to do is import the class and voilà- there’s your Singleton.</p>
<p><img src='http://pixelwelders.com/blog/wp-content/uploads/2008/04/singleton_village.jpg' alt='The Village of Singleton' style='float:right; margin:.5em 0em 1.5em 1.5em;padding:0;'/></p>
<p>It works this way because the class itself keeps a static reference to the only instance of itself.  So instead of calling the constructor to get a reference to a new instance, you call the <code>SingletonClassName.instance</code> method to get a reference to the <em>already-created</em> instance.  If that doesn&#8217;t make sense, here&#8217;s an example.  This first piece of code is what a normal ScoreKeeper class would look like.  With this structure, you can use that syntax that everyone knows and loves, <code>new ScoreKeeper()</code>, which returns a brand new ScoreKeeper every time it&#8217;s called.</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript">package
<span style="color: #66cc66;">&#123;</span>
	<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ScoreKeeper
	<span style="color: #66cc66;">&#123;</span>
		<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> ScoreKeeper<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
		<span style="color: #66cc66;">&#123;</span>
			<span style="color: #0066CC;">trace</span><span style="color: #66cc66;">&#40;</span> <span style="color: #ff0000;">&quot;new ScoreKeeper&quot;</span> <span style="color: #66cc66;">&#41;</span>;
		<span style="color: #66cc66;">&#125;</span>
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>But suppose you wanted to ensure that there was only one ScoreKeeper, and you wanted to be able to easily access it from any location in your program.  That means two things: A) the constructor can only be called once, and B) you need to keep track of the new ScoreKeeper that one time the constructor <em>does</em> get called.  What good is having one instance of a class if you can&#8217;t get to it?  So here&#8217;s the Singleton version of the above class:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript">package
<span style="color: #66cc66;">&#123;</span>
	<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ScoreKeeper
	<span style="color: #66cc66;">&#123;</span>
		<span style="color: #0066CC;">private</span> <span style="color: #0066CC;">static</span> <span style="color: #000000; font-weight: bold;">var</span> _instance:ScoreKeeper;
&nbsp;
		<span style="color: #0066CC;">public</span> <span style="color: #0066CC;">static</span> <span style="color: #000000; font-weight: bold;">function</span> <span style="color: #0066CC;">get</span> instance<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
		<span style="color: #66cc66;">&#123;</span>
			<span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span> <span style="color: #66cc66;">!</span>_instance <span style="color: #66cc66;">&#41;</span>
			<span style="color: #66cc66;">&#123;</span>
				_instance = <span style="color: #000000; font-weight: bold;">new</span> ScoreKeeper<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
			<span style="color: #66cc66;">&#125;</span>
&nbsp;
			<span style="color: #b1b100;">return</span> _instance;
		<span style="color: #66cc66;">&#125;</span>
&nbsp;
		<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> ScoreKeeper<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
		<span style="color: #66cc66;">&#123;</span>
			<span style="color: #0066CC;">trace</span><span style="color: #66cc66;">&#40;</span> <span style="color: #ff0000;">&quot;new ScoreKeeper!&quot;</span> <span style="color: #66cc66;">&#41;</span>;
		<span style="color: #66cc66;">&#125;</span>	
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>There are two differences here: the static variable <code>_instance</code> and the static method <code>get instance()</code>.  The <code>_instance</code> variable is where the actual instance of this class is stored.  And the <code>get instance()</code> method, of course, enables you to access this instance.  So to access this Singleton, you would use:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript">ScoreKeeper.<span style="color: #006600;">instance</span>;</pre></div></div>

<p>And to call any methods or properties of the Singleton, you would use this syntax:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript">ScoreKeeper.<span style="color: #006600;">instance</span>.<span style="color: #006600;">addScore</span><span style="color: #66cc66;">&#40;</span> <span style="color: #cc66cc;">50</span> <span style="color: #66cc66;">&#41;</span>;
<span style="color: #0066CC;">trace</span><span style="color: #66cc66;">&#40;</span> ScoreKeeper.<span style="color: #006600;">instance</span>.<span style="color: #006600;">score</span> <span style="color: #66cc66;">&#41;</span>;</pre></div></div>

<p>This of course assumes that your class has a public method called <code>addScore()</code> and a public property called <code>score</code>.  You can get to any public methods or properties this way.</p>
<p>This also adds one more layer, called <em>lazy initialization</em>.  Look in the <code>get instance()</code> method, and notice that before it returns a reference to the Singleton, it checks to see if that reference exists.  If so, it simply returns it.  If not, it creates it first and <em>then</em> returns it.  Either way, you&#8217;re guaranteed to get the one existing instance.</p>
<p>There is one problem remaining- if you were so inclined, you could still call the constructor without going through <code>get instance()</code>, which would of course result in <em>two</em> Singletons.  And as we discussed above, making two of something makes it not a Singleton anymore.  So how can we prevent this?  There are a few ways I&#8217;ve seen floating around, but the simplest is this:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript">package
<span style="color: #66cc66;">&#123;</span>
	<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">class</span> ScoreKeeper
	<span style="color: #66cc66;">&#123;</span>
		<span style="color: #0066CC;">private</span> <span style="color: #0066CC;">static</span> <span style="color: #000000; font-weight: bold;">var</span> _instance:ScoreKeeper;
&nbsp;
		<span style="color: #0066CC;">public</span> <span style="color: #0066CC;">static</span> <span style="color: #000000; font-weight: bold;">function</span> <span style="color: #0066CC;">get</span> instance<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
		<span style="color: #66cc66;">&#123;</span>
			<span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span> <span style="color: #66cc66;">!</span>_instance <span style="color: #66cc66;">&#41;</span>
			<span style="color: #66cc66;">&#123;</span>
				_instance = <span style="color: #000000; font-weight: bold;">new</span> ScoreKeeper<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>;
			<span style="color: #66cc66;">&#125;</span>
&nbsp;
			<span style="color: #b1b100;">return</span> _instance;
		<span style="color: #66cc66;">&#125;</span>
&nbsp;
		<span style="color: #0066CC;">public</span> <span style="color: #000000; font-weight: bold;">function</span> ScoreKeeper<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>
		<span style="color: #66cc66;">&#123;</span>
			<span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span> _instance <span style="color: #66cc66;">&#41;</span>
			<span style="color: #66cc66;">&#123;</span>
				<span style="color: #0066CC;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #0066CC;">Error</span><span style="color: #66cc66;">&#40;</span> <span style="color: #ff0000;">&quot;Singleton already exists- use get instance() to access&quot;</span> <span style="color: #66cc66;">&#41;</span>;
			<span style="color: #66cc66;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #66cc66;">&#123;</span>
				<span style="color: #0066CC;">trace</span><span style="color: #66cc66;">&#40;</span> <span style="color: #ff0000;">&quot;new ScoreKeeper!&quot;</span> <span style="color: #66cc66;">&#41;</span>;
			<span style="color: #66cc66;">&#125;</span>
		<span style="color: #66cc66;">&#125;</span>	
	<span style="color: #66cc66;">&#125;</span>
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>The new lines are in the constructor.  The <code>get instance()</code> method still only calls the constructor once, but if you forget it&#8217;s a Singleton and call the constructor later, you get a runtime error.</p>
<p>There are also a couple more complicated ways of ensuring that your Singleton is in fact a Singleton, but I haven&#8217;t lost too much sleep over over it.  I usually even leave out the check in the constructor.  Just remember that if it has <code>_instance</code> and <code>get instance()</code>, and a big comment up at the top that says &#8220;SINGLETON!&#8221;, it&#8217;s probably a Singleton.</p>
]]></content:encoded>
			<wfw:commentRss>http://pixelwelders.com/blog/best-practices/2008/art-and-beauty-of-singletons-in-as3/feed/</wfw:commentRss>
		</item>
		<item>
		<title>MXML Singletons in Flex 3</title>
		<link>http://pixelwelders.com/blog/flex/2008/mxml-singletons-in-flex-3/</link>
		<comments>http://pixelwelders.com/blog/flex/2008/mxml-singletons-in-flex-3/#comments</comments>
		<pubDate>Thu, 10 Apr 2008 09:04:27 +0000</pubDate>
		<dc:creator>Zack Jordan</dc:creator>
		
		<category><![CDATA[ActionScript 3.0]]></category>

		<category><![CDATA[Design Patterns]]></category>

		<category><![CDATA[Flex]]></category>

		<category><![CDATA[MXML]]></category>

		<guid isPermaLink="false">http://pixelwelders.com/blog/flex/2008/mxml-singletons-in-flex-3/</guid>
		<description><![CDATA[Okay, so I've been putting together a little image-viewer component in Flex, and I wanted it to load one data model that all other components would share.  Sounds like a job for a Singleton, right?  However, I also wanted to instantiate said model from MXML, which adds some kinks.  In fact, I've <a href="http://www.onflex.org/ted/2007/01/singleton-in-mxml.php">heard it said</a> that it's not possible at all.  And after some trial and error, I found that apparently it is possible- you just have to hack around a little bit.  ]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;re not clear on what a Singleton is, try glancing through my brief yet poignant article here: <a href="http://pixelwelders.com/blog/best-practices/2008/art-and-beauty-of-singletons-in-as3/" >The Art and Beauty of Singletons</a>.</p>
<h3>Creating a Singleton through MXML</h3>
<p>	Okay, so I&#8217;ve been putting together a little image-viewer component in Flex, and I wanted it to load one data model that all other components would share.  Sounds like a job for a Singleton, right?  However, I also wanted to instantiate said model from MXML, which adds some kinks.  In fact, I&#8217;ve <a href="http://www.onflex.org/ted/2007/01/singleton-in-mxml.php" onclick="javascript:pageTracker._trackPageview('/outbound/article/http://www.onflex.org/ted/2007/01/singleton-in-mxml.php');">heard it said</a> that it&#8217;s not possible at all.  And after some trial and error, I found that apparently it is possible- you just have to hack around a little bit.  </p>
<p>If you instantiate your class (or &#8220;component&#8221;) through MXML, Flex will automatically call its constructor.  Typically, this is a bad thing because you don&#8217;t call constructors directly in Singletons- instead of calling a method that returns a <em>new</em> object (i.e. a constructor), you call a method that returns a reference to an already-created object (<code>getInstance()</code> or <code>instance()</code>).  Flex won&#8217;t do that for you.  However, this is not a deal-breaker.  To make that class a Singleton, you just need to make sure that the constructor is only called once.</p>
<p>So, set up your Singleton like normal:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript"><span style="color: #0066CC;">private</span> <span style="color: #0066CC;">static</span> <span style="color: #000000; font-weight: bold;">var</span> _instance: DataModel = <span style="color: #000000; font-weight: bold;">null</span>;
<span style="color: #0066CC;">public</span> <span style="color: #0066CC;">static</span> <span style="color: #000000; font-weight: bold;">function</span> <span style="color: #0066CC;">get</span> instance<span style="color: #66cc66;">&#40;</span><span style="color: #66cc66;">&#41;</span>: DataModel
<span style="color: #66cc66;">&#123;</span>
	<span style="color: #b1b100;">return</span> _instance;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>Then, in the constructor of said Singleton, add the following:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript"><span style="color: #b1b100;">if</span> <span style="color: #66cc66;">&#40;</span> <span style="color: #66cc66;">!</span>_instance <span style="color: #66cc66;">&#41;</span>
<span style="color: #66cc66;">&#123;</span>
	_instance = <span style="color: #0066CC;">this</span>;
<span style="color: #66cc66;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #66cc66;">&#123;</span>
	<span style="color: #0066CC;">throw</span> <span style="color: #000000; font-weight: bold;">new</span> <span style="color: #0066CC;">Error</span><span style="color: #66cc66;">&#40;</span> <span style="color: #ff0000;">&quot;DataModel is a Singleton: only one instance allowed.&quot;</span> <span style="color: #66cc66;">&#41;</span>;
<span style="color: #66cc66;">&#125;</span></pre></div></div>

<p>All I&#8217;ve done here is move the creation of the Singleton from the <code>get instance()</code> method to the constructor.  And if the constructor is called more than once, it throws an error.  Now you can instantiate the class through MXML, just like any other component.</p>

<div class="wp_syntax"><div class="code"><pre class="xml"><span style="color: #009900;"><span style="font-weight: bold; color: black;">&lt;model:DataModel</span>
		<span style="color: #000066;">id</span>=<span style="color: #ff0000;">&quot;dataModel&quot;</span>
		<span style="color: #000066;">xmlURL</span>=<span style="color: #ff0000;">&quot;fileName.xml&quot;</span> <span style="font-weight: bold; color: black;">/&gt;</span></span></pre></div></div>

<p>Meanwhile in Actionscriptland, you can refer to this instance of your class just like it was a normal Singleton:</p>

<div class="wp_syntax"><div class="code"><pre class="actionscript">	<span style="color: #0066CC;">trace</span><span style="color: #66cc66;">&#40;</span> DataModel.<span style="color: #006600;">instance</span> <span style="color: #66cc66;">&#41;</span>; <span style="color: #808080; font-style: italic;">// traces &quot;[object DataModel]&quot;</span></pre></div></div>

<p>	Plus, if you try to create another instance, be it through MXML or through ActionScript, you&#8217;ll get a good ol&#8217; runtime error.  You’ll have to wait until runtime to see it, but that’s certainly better than nothing, right?</p>
]]></content:encoded>
			<wfw:commentRss>http://pixelwelders.com/blog/flex/2008/mxml-singletons-in-flex-3/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
