JavaScript design pattern-monolithic (Singleton) Pattern

Source: Internet
Author: User

JavaScript design pattern-monolithic (Singleton) Pattern
Design Pattern-Single Instance Pattern

1. Introduction

Starting from this chapter, we will gradually introduce the implementation of various design patterns used in JavaScript. Here I will not introduce the theory of the pattern too much, but will only focus on implementation. OK.

In the eyes of traditional development engineers, Singleton is to ensure that there is only one instance for a class. The implementation method is to first determine whether the instance exists or not. If the instance exists, it is directly returned. If the instance does not exist, it is created and then returned, this ensures that a class has only one instance object. In JavaScript, a singleton acts as a namespace provider and provides a unique access point from the global namespace to access this object.

2. Simple monomer and closure Monomer

In JavaScript, there are many ways to implement singleton. One of the simplest ways is to use the object literal method, which can contain a large number of attributes and methods:

<Script> // standalone mode (sigleton) -- new () cannot be created (); because it already exists/* 1. Simple monomer -- the mode of the object independent variable * // * var Sigleton = {attr1: true, attr2: 10, method1: function () {alert (method 1) ;}, method2: function () {alert (method 2) ;}}; alert (Sigleton. attr1); // The single mode is mainly to divide the namespace and distinguish the code var BHX = BHX |{}; BHX. sigleton = {attr1: true, attr2: 10, method1: function () {alert (I am method 1) ;}, method2: function () {alert (I am method 2) ;}}; BHX. sigleton. method1 (); * // * 2 , Closure monomer --- borrow a closure to wear a simple body (Closure's main purpose: to protect data) * // namespace -- block-level scope Implementation/* (function test () {alert (11) ;}) () */var BHX = BHX ||{}; BHX. sigleton2 = (function () {// the function of using a closure is to encapsulate its own private attributes and prevent external access. Only return is exposed. Var a1 = true; var a2 = 10; var f1 = function () {alert (function f1) ;}; var f2 = function () {alert (function f2 );}; // assign the block-level scope to Sigleton2 with a return statement. Return {attr1: true, attr2: 10, method1: function () {return f1 () ;}, method2: function () {return f2 ;}};})(); alert (BHX. sigleton2.attr1); BHX. sigleton2.method1 (); </script>

The above code is good, but if we want to initialize it only when it is used, what should we do? To save resources, we can initialize the code using another constructor, as shown below:

3. inert monomer and branch Monomer
<Script>/* 3. inert monomer --- (similar to the closure monomer). However, variables can be used to control the content to be returned, rather than all, this will benefit a large project. * // The namespace var BHX = BHX ||{}; BHX. base = (function () {// use private variables to control the returned single object var uniqueInstance; // undefined // function init () {var a1 = true; var a2 = 10; var f1 = function () {alert (function f1) ;}; var f2 = function () {alert (function f2) ;}; return {attr1: true, attr2: 10, method1: function () {return f1 () ;}, Method2: function () {return f2 ;};}; return {getInstance: function () {if (! UniqueInstance) {// if it does not exist, create the uniqueInstance = init () ;}; return uniqueInstance ;}}) (); // BHX. base. getInstance (). method1 ();/* 4. Branch monomer -- similar to swich if else, it can be used for Difference Detection in underlying framework browsers */var Ext = Ext | {}; var diff = true; Ext. more = (function () {var ObjA = {// Firefox browser // attribute 1 attr1: Firefox property 1 // attribute 2 // method 1 // method 2 }; var ObjB = {// attribute 1 attr1: IE attribute 1 // attribute 2 // method 1 // method 2}; return (diff )? ObjA: ObjB;}) (); alert (Ext. More. attr1); </script>

I know how to implement the Singleton, but what kind of scenarios is better for Singleton? In fact, Singleton is generally used for communication and coordination between systems in various modes. The following code is a singleton best practice:

4. Best practices
Var SingletonTester = (function () {// parameter: a set of parameters passed to the Singleton (args) {// set The args variable to the received parameter or to null (if not provided) var args = args ||{}; // set the name parameter this. name = 'singletontester'; // set the pointX value this. pointX = args. pointX | 6; // get from the received parameter, or set it to the default value // set the pointY value this. pointY = args. pointY | 10;} // var instance of the instance container; var _ static = {name: 'singletontester', // method for obtaining the instance // getInstance of Singleton is returned: function (args) {if (instance = undefined) {instance = new Singleton (args) ;}return instance ;}; return _ static ;})(); var singletonTest = SingletonTester. getInstance ({pointX: 5}); console. log (singletonTest. pointX); // output 5
 

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.