1、 The singleton pattern

Make sure there is only one instance of a class , And provide a global access point to access it

1.1 Traditional singleton mode

var Singleton=function(name){
this.name=name;
}
Singleton.prototype.getName=function(){
alert(this.name);
}
Singleton.getInstance=(function(){
var instance=null;
return function (name) {
if(!instance){
instance=new Singleton(name);
}
return instance;
}
})(); var a=Singleton.getInstance('sven1');
var b=Singleton.getInstance('sven2');
alert(a===b);//true

1.2 JavaScript The singleton pattern in

The core of the singleton model is Make sure there is only one instance , And provide global access
JavaScript in , You can use global variables as singletons
var a={};
Creating objects in this way a, This object a It's unique , And can be accessed in a global scope
Global variables are prone to namespace pollution , Using a namespace reduces the number of global variables

var namespace1={
a:function(){
alert(1);
},
b:function(){
alert(2);
}
};

1.3 Application, for example, -- Inertia alone

To click “ land ” Button pop-up login box as an example

<html>
<body>
<button id="loginBtn" > land </button>
</body>
<script>
var createLoginLayer=(function(){
var div;
return function(){
if(!div){
div=document.createElement('div');
div.innerHTML=' I'm landing at the pontoon ';
div.style.display='none';
document.body.appendChild(div);
}
return div;
}
})();
document.getElementById('loginBtn').onclick=function(){
var loginLayer=createLoginLayer();
loginLayer.style.display='block';
};
</script>
</html>

The above example violates the single responsibility principle , Creating objects and managing singleton logic are coupled

var getSingle= function (fn) {
var result;
return function () {
return result || (result = fn.apply(this,arguments));
}
};
var createLoginLayer=function(){
var div=document.createElement('div');
div.innerHTML=' I'm the landing window ';
div.style.display='none';
document.body.appendChild(div);
return div;
};
var createSingleLoginLayer=getSingle(createLoginLayer());
document.getElementById('loginBtn').onclick=function(){
var loginLayer=createSingleLoginLayer();
loginLayer.style.display='block';
};
// When you need to create unique iframe Used to dynamically load third-party pages
var createSingleIframe=getSingle(function () {
var iframe=document.createElement('iframe');
document.body.appendChild(iframe);
});
document.getElementById('loginBtn').onclick=function(){
var loginLayer=createSingleIframe();
loginLayer.src='http://www.google.com';
};

《JavaScript Design patterns and development practices 》 More articles about the single example mode of reading notes

  1. JavaScript Design patterns and development practices —— Reading notes 1. Higher order function ( On )

    Ashamed to speak ,4 It hasn't been updated for more than a month .4 I've been busy since January , The paper . Bi Jian . Graduation travel and other things take up a lot of time , After graduation, I started my busy work , I want to blog all the time , But I haven't been able to calm down and write . I've been watching <Java ...

  2. JavaScript Design patterns and development practices —— Reading notes 1. Higher order function ( Next )

    The first part mainly introduces the common forms of higher-order functions , This section focuses on the advanced applications of higher-order functions . 1.currying currying It refers to the coriolisation of functions , Also called partial evaluation . One currying The function will take some parameters first , But not immediately , ...

  3. Javascript Design pattern and development practice reading notes (1-3 Chapter )

    Chapter one Object oriented Javascript 1.1 The application of polymorphism in object-oriented design    The fundamental advantage of polymorphism is , You don't have to ask people “ What kind of you are ” And then call a behavior of the object according to the answer -- You just call the behavior , The rest of it ...

  4. javascript Design patterns and development practice reading notes (8)—— Observer mode

    Release - A subscription model , It's also called observer mode : Defines a one-to-many dependency between objects , When the state of an object changes , All objects that depend on it will be notified . stay JavaScript In development , We usually use the event model instead of the traditional observer model . ...

  5. javascript Design patterns and development practice reading notes (7)—— Iterator pattern

    Iterator pattern : Provides a way to access elements of an aggregate object in sequence , Without exposing the internal representation of the object . The iterator pattern separates the iterative process from the business logic , After using the iterator pattern , Even if you don't care about the internal structure of the object , You can also follow the order ...

  6. javascript Design patterns and development practice reading notes (6)—— The proxy pattern

    The proxy pattern : Is to provide a substitute or a place holder for an object , In order to control access to it . The key to the agency model is , When the customer is inconvenient to directly access an object or does not meet the needs , Provide a surrogate object to control access to this object , The client is actually visiting the stand in ...

  7. javascript Design patterns and development practice reading notes (4)—— The singleton pattern

    Definition The singleton pattern : Make sure there is only one instance of a class , And provide a global access point to access it . say concretely , It is to ensure that some objects have and only have one , For example, thread pool . Global cache . In the browser window Object etc. . stay js The singleton pattern is very useful , For example, login. ...

  8. 《JavaScript Design patterns and development practices 》 Note chapter eight Release - A subscription model

    Chapter viii. Release - A subscription model Release - Subscription mode description Release - Subscription mode is also called observer mode , It defines a one to many dependency between objects , When the state of an object changes , All objects that depend on it will be notified . Release - Subscription mode can be widely used in ...

  9. 《JavaScript Design patterns and development practices 》 Chapter one of the notes

    Chapter one Object oriented JavaScript Dynamic type language and duck type Programming languages can be roughly divided into two categories according to data types : Static type language . Dynamic type language . Static type language : The type of the variable is determined at compile time . advantage : At compile time, you'll find ...

  10. javascript Design patterns and development practice reading notes (5)—— The strategy pattern

    The strategy pattern : Define a set of algorithms , Encapsulate them one by one , And make them interchangeable . My understanding is to encapsulate various methods into functions , There is also a common function that can call these methods . The advantage of this is that it can digest the internal branch judgment , Make code efficient ...

Random recommendation

  1. T-SQL Common use of practical query SQL sentence

    Delete all tables in the database : declare @sql varchar() begin SELECT @sql='drop table ' + name FROM sysobjects WHERE (type ...

  2. Gray Code

    Gray Code The gray code is a binary numeral system where two successive values differ in only one bi ...

  3. [Tex Learning notes ] Ellipsis in matrix input

    \usepackage{enumerate,mathdots} $\iddots$

  4. Objective-C 【 Read and write strings from a file ( Direct reading and writing / adopt NSURL Reading and writing )】

    ——————————————————————————————————————————— Read and write strings from a file ( Direct reading and writing / adopt NSURL Reading and writing ) #import <Foundation/Foundati ...

  5. HDU ACM Eight

    Topic link :http://acm.hdu.edu.cn/showproblem.php?pid=1043 Background of problem solving : See eight digital problems , No idea , By chance, I found that I had solved a similar problem when I looked at the previous problem , No ...

  6. Java Web Development FAQs

    One .Tomcat Common server startup problems :(1).Java_home environment variable , because tomcat Server's bin Some of the contents jar The file must be used to java Class library , So you have to configure Java_home environment variable .(2). End ...

  7. Jasper_table_resolve get multiple copies of table in detail band issue

    resolve method: (1) put table component into the Title band / Page Header band / Summary band, not i ...

  8. ORACLE profile Column 4 --CREATE PROFILE

    This blog is ORACLE profile Part four of the series . mainly , Suppose you create profile While using profile Resources and password control CREATE PROFILE Note: Oracle reco ...

  9. OpenJudge NOI 4976 COINS

    http://noi.openjudge.cn/ch0207/4976/ describe The astronauts Bob One day I came to Mars , He has the habit of collecting coins . So he collected all the coins on Mars , Altogether n Kind of , There's only one of each : Noodles ...

  10. codeforce864d

    D. Make a Permutation! time limit per test 2 seconds memory limit per test 256 megabytes input stand ...