<?xml version="1.0" encoding="UTF-8"?>
<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/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Ashita.org &#187; Singleton</title>
	<atom:link href="http://www.ashita.org/tag/singleton/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.ashita.org</link>
	<description></description>
	<lastBuildDate>Thu, 22 Apr 2010 17:21:34 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Singletons in JavaScript</title>
		<link>http://www.ashita.org/singletons-in-javascript/</link>
		<comments>http://www.ashita.org/singletons-in-javascript/#comments</comments>
		<pubDate>Thu, 24 Sep 2009 07:13:57 +0000</pubDate>
		<dc:creator>Jonathan Fingland</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[closures]]></category>
		<category><![CDATA[Singleton]]></category>

		<guid isPermaLink="false">http://ashita.org/?p=329</guid>
		<description><![CDATA[I use singletons all over the PirateQuesting code, but I&#8217;ve never explained the idea here, nor how they are different from singletons in other languages.
Anyone familiar with common design patterns knows how singletons work in the vast majority of languages.  For a PHP example, see this post. 
In JavaScript there are basically two main [...]]]></description>
			<content:encoded><![CDATA[<p>I use singletons all over the <a href="http://pq.ashita.org">PirateQuesting</a> code, but I&#8217;ve never explained the idea here, nor how they are different from singletons in other languages.</p>
<p>Anyone familiar with common design patterns knows how singletons work in the vast majority of languages.  For a PHP example, see <a href="http://www.ashita.org/singletons-in-php/">this post</a>. </p>
<p>In JavaScript there are basically two main ways to create a singleton. One is use immediate instantiation so that the class may not be instantiated again. The second is closer to the traditional singleton pattern, however, since there are no private members or constructors, we can get around this by using a nested &#8216;class&#8217; constructor &#8212; and there are two ways to accomplish this.</p>
<p>The first way is done as follows:</p>
<pre>
var singleton = new (function Singleton() {
                               this.value = 12;
                             } )();

alert(singleton.value); // alerts 12;

var singly = new Singleton(); // Singleton is not defined.

alert(singleton instanceof Singleton); // Singleton is not defined
</pre>
<p>In the above, the constructor name, Singleton, isn&#8217;t really necessary. While it can&#8217;t be used to instantiate the Singleton again, it also can&#8217;t be used with <code>instanceof </code>or <code>typeof</code> so feel free to leave it out if you want; leaving it in, does make it more obvious what is happening though.</p>
<p>And the second way (version 1):</p>
<pre>
var Singleton = (function () {
  var instance = null;

  function Singleton() {
    this.value = 12;
  }

  this.getInstance = function () {
    if (instance === null) {
      instance = new Singleton();
    }
    return instance;
  }
})();

var singleton = Singleton.getInstance();
alert(singleton.value); // alerts 12;

var singly = new Singleton(); // Singleton is not a construct

alert(singleton instanceof Singleton); //invalid 'instanceof' operand Singleton
</pre>
<p>The above is just an anonymous function being called immediately (note the <code>()</code> after the function declaration). Inside the function it declares a pseudo-private member called <code>instance</code>, a pseudo-private constructor, <code>Singleton</code>, and a <code>getInstance</code> method. The <code>getInstance</code> method can see <code>instance</code> due to closure, while the outside world has no idea that it exists.</p>
<p>And finally, the second way (version 2):</p>
<pre>
var Singleton = {

  getInstance : (function() {

    var instance;
    function Singleton() {
      this.value = 12;
    }

    return function () {
      if (instance == null) {
	    instance = new Singleton();
      }
      return instance;

    }

  })()
}

var singleton = Singleton.getInstance();
alert(singleton.value);

var singly = new Singleton(); // Singleton is not a constructor

alert(singleton instanceof Singleton); //invalid 'instanceof' operand Singleton
</pre>
<p>In this final example, all of the logic is put into the <code>getInstance</code> function which is the result of a self-calling function which itself returns a function. Yeah, it&#8217;s a little hard to follow, but basically the returned function has visibility of <code>instance </code>and the <code>Singleton </code>constructor due to closure.</p>
<p>As a closing note, it&#8217;s worth pointing out that although all of the above methods do not permit a second instance construction, they also do not allow use of <code>typeof </code>or <code>instanceof </code>for type verification.</p>
<h3>Update</h3>
<p>Based on a comment below by Peter Robinett, I&#8217;ve come up with a different way to do this, which allows for <code>instanceof</code> and <code>typeof</code> and seems to be an all-round good solution to the problem. It does not, however use the classical <code>getInstance</code> method, but works well all the same.</p>
<pre>
var Singleton = function () {
  var instantiated = false;

  return function () {
    if (instantiated) {
      throw "Singleton already instantiated";
    }
    instantiated = true;
    this.value=12;
    }
}()

var singleton = new Singleton();
alert(singleton.value);    //alerts 12
alert(singleton instanceof Singleton);  alerts true 

var singly = new Singelton(); //throws exception and cannot be instantiated
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.ashita.org/singletons-in-javascript/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Singletons in PHP</title>
		<link>http://www.ashita.org/singletons-in-php/</link>
		<comments>http://www.ashita.org/singletons-in-php/#comments</comments>
		<pubDate>Wed, 23 Sep 2009 02:59:09 +0000</pubDate>
		<dc:creator>Jonathan Fingland</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Singleton]]></category>

		<guid isPermaLink="false">http://ashita.org/?p=331</guid>
		<description><![CDATA[I write PHP regularly in my job, but this is the first post on Ashita.org on a PHP subject. One interesting problem recently was how to make Singletons in PHP from a generic base class and extended where necessary. First, an introduction: Singletons are an incredibly common and useful design pattern. Singletons are used to [...]]]></description>
			<content:encoded><![CDATA[<p>I write PHP regularly in my job, but this is the first post on Ashita.org on a PHP subject. One interesting problem recently was how to make Singletons in PHP from a generic base class and extended where necessary. First, an introduction: Singletons are an incredibly common and useful design pattern. Singletons are used to ensure there is only one instance of a class and the class cannot be instantiated directly from outside the class.</p>
<ul class='structure'>
<li>
<h3>Simple Case</h3>
<p>In PHP, the singleton pattern is as easy as making a class with a private or protected constructor and a static method to get the single instance.</p>
<pre><code class='javascript'>
class Singleton
{
  private $instance;

  private function __construct()
  {
  }

  private function __clone()
  {
    //do nothing
  }

  public static function getInstance()
  {
    if (is_null(self::$instance))
    {
      self::$instance = new self();
    }
    return self::$instance;
  }
}</code>
</pre>
<ul class='structure'>
<li>
<h4>Note</h4>
<p>One thing to note about the code above is the <code>__clone()</code> method. Unless overridden, the default __clone() method creates a new object with all of the properties copied over. Obviously, this goes against the principles of a singleton &#8212; there should be only one instance.
</li>
</ul>
<p>This technique allows the class author to ensure only one instance is available and that any changes made to it are shared by all references to this object, but what if we wanted to use this pattern more than once. Wouldn&#8217;t it be better to extend this class? Doing so would require some changes&#8230; (and in this implementation, it requires php 5.3 or higher)
</li>
<li>
<h3>Extendable Singleton</h3>
<pre><code class='javascript'>
abstract class Singleton
{
  public static function getInstance()
  {
    $class = get_called_class();
    if (is_null($class::$instance))
    {
      $class::$instance = new $class();
    }
    return $class::$instance;
  }

}

class Database extends Singleton
{

  protected static $instance;

  protected function __construct()
  {
    //do DB init work here
  }

  private function __clone()
  { }

  //include functions to act on DB here

}
</code></pre>
<p>basically, the only thing classes extending Singleton would need to do is mark their <code>__construct </code>method protected, their <code>__clone</code> method can remain private, and to include a <code>protected static $instance</code> class variable. Further simplifications <em>could</em> be made, but it seems a good base to work from. (Note that the above example requires a somewhat quirky behaviour in php that allows subclasses to inherit static methods.)
</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.ashita.org/singletons-in-php/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
