JavaScript design mode communication (i): Singleton pattern

Source: Internet
Author: User
Tags constructor implement return variable access
javascript| Design

Even in a simple scripting language, a good pattern can get very "graceful" code and high efficiency.
Especially for the B/s system with high interaction requirement, it is necessary to optimize the code with the design pattern.

Single-piece mode (Singleton pattern) is a very basic and important creation pattern.
The responsibility of a "single piece" is to ensure that a class has and has only one instance, and provides a global access point to access it.
In the process of programming, there are many situations where you need to ensure that a class can have only one instance.

In a traditional programming language, the easiest way to make a class have only one instance is to embed the static variable in the class, set the variable in the first instance, and check each entry into the constructor, regardless of the number of instances of the class, and the static variable can have only one instance. To prevent a class from being initialized multiple times, the constructor is declared private so that only one instance of the static method can be created.

In JavaScript, although we can still specify static methods to construct objects, we cannot use the constructor's "private" to prohibit the generation of multiple instances, so it is not as easy to fully implement Singleton.

Take a look at the following example:

The following content is program code
<SCRIPT>
Function singletonobject ()
{
 singletonobject.prototype.methoda = function ()
 {
  alert (' MethodA ');
&NBSP}
 singletonobject.prototype.methodb = function ()
 {
  alert (' MethodB ');
&NBSP}
 singletonobject.instance = this;
}
Singletonfactory = new Object ();
Singletonfactory.getinstance = function ()
{
 if (singletonobject.instance = null)
   return new Singletonobject ();
 else
  return singletonobject.instance;
}

var Insta = singletonfactory.getinstance ();
var instb = singletonfactory.getinstance ();
Insta.methoda ();
Instb.methoda ();
Alert (Insta = = INSTB);//Success
var INSTC = new Singletonobject ();
Instc.methoda ();
Alert (Insta = = INSTC);//Failed
</script>

The example above attempts to implement the singleton pattern in a traditional way, and by calling Singletontest.getinstance () to get an object does guarantee a "unique instance", however, the failure of this example is that it does not effectively prohibit the construction of singleton objects, so if we manually add new to the program code Singletonobject () can still get more than one object and cause the schema to fail.

An improved alternative is as follows:
The following is the program code
<SCRIPT>
Function singletonobject ()
{
 if ( Singletonobject.instance!= null)
 {
  alert ("Cannot create multiple singleton instances!");
  throw new Error ();
 }
 singletonobject.prototype.methoda = function ()
 {
  alert (' MethodA ');
&NBSP}
 singletonobject.prototype.methodb = function ()
 {
  alert (' MethodB ');
&NBSP}
 singletonobject.instance = this;
}
Singletonfactory = new Object ();
Singletonfactory.getinstance = function ()
{
 if (singletonobject.instance = null)
   return new Singletonobject ();
 else
  return singletonobject.instance;
}

var Insta = singletonfactory.getinstance ();
var instb = singletonfactory.getinstance ();
Insta.methoda ();
Instb.methoda ();
Alert (Insta = = INSTB); Success
Try
{var instc = new Singletonobject ();} Throw an exception
catch (E)
{alert (' The system successfully throws an exception, blocking the construction of the INSTC! ');}
</script>

This prevents a user from manually throwing an exception when he or she tries to create multiple objects on its own. But there's a little bit of a violation of "original intention", that is, the basic condition that "a unique instance must be constructed by static method" is not met. Because the user can at the beginning or can use the new operator to construct the object, such as at the beginning of the write var Insta = new Singletonobject () to construct Insta does not cause an exception to throw, this is not to say is a flaw in this approach.

So we think further and get the following third method, which skillfully exploits the feature of the "anonymous" function to prohibit access to the Singletonobject class constructor, which can be said to simulate the properties of private constructors. Thus, the problem of using JavaScript to realize singleton pattern is solved perfectly.

The following is the program code
<script>
(function () {
Instance declared
Singletonfactory Interface
Singletonfactory = {
Getinstance:getinstance
}

Private classes
function Singletonobject ()
{
SingletonObject.prototype.methodA = function ()
{
Alert (' MethodA ');
}
SingletonObject.prototype.methodB = function ()
{
Alert (' MethodB ');
}
Singletonobject.instance = this;
}

Singletonfactory implementions
function getinstance ()
{
if (singletonobject.instance = null)
return new Singletonobject ();

Else
return singletonobject.instance;
}

})();

var insta = null;
Try
{
Alert ("Attempts to construct an instance through new Singletonobject ()!") ");
Insta = new Singletonobject ();
}
catch (E) {alert ("Singletonobject constructor cannot be accessed externally, the system throws an exception!") ");}

Insta = Singletonfactory.getinstance (); Obtained by the static method defined on the factory
var instb = singletonfactory.getinstance ();
Insta.methoda ();
Instb.methoda ();

Alert (Insta = = INSTB); Success

var INSTC = null;
Try
{
Alert ("Attempts to construct an instance through new Singletonobject ()!") ");
INSTC = new Singletonobject ();
}
catch (E) {alert ("Singletonobject constructor cannot be accessed externally, the system throws an exception!") ");}
</script>



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.