Want to know the implementation and application of single instance mode in the front end?

Cheng Huan x 2021-09-15 06:28:22
want know implementation application single


The singleton pattern , Also called Single mode , One of the patterns of creation .

When applying this mode , Classes of singleton objects must ensure that only one instance exists . Many times the entire system only needs to have one global object , This helps us to coordinate the behavior of the system as a whole .

For example, in a server program , The configuration information for this server is stored in a file , This configuration data is read uniformly by a singleton object , This singleton object is then used by other objects in the service process to obtain the configuration information . This approach simplifies configuration management in complex environments .

Idea of realizing singleton mode

A class can return an object and a reference ( Always the same ) And a way to get the instance ( Must be a static method , Usually use getInstance The name );

When we call this method , Return the reference if the reference held by the class is not empty , If the reference maintained by a class is empty, an instance of the class is created and the instance reference is given to the reference maintained by the class ;

At the same time, we also define the constructor of this class as a private method , In this way, the code elsewhere cannot instantiate the class's object by calling the class's constructor , Only static methods provided by this class can get the unique instance of this class .

The following uses JavaScript Implement singleton mode :

var Singleton = function (name) {
 this.name = name;
}
​
Singleton.instance = null;
Singleton.prototype.getName = function() {
 alert(this.name);
}
​
Singleton.getInstance = function(name) {
 if ( !this.instance ) {
   this.instance = new Singleton(name);
}
 return this.instance
}
​
var a = Singleton.getInstance('sven1');
var b = Singleton.getInstance('sven2');
​
alert( a === b ); // true
​
// perhaps
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
 Copy code 

Can be applied to thread pool 、 Global cache 、 In the browser window object 、 Floating window .

Javascript Practice of singleton mode

Global variables conform to this singleton pattern , However, it is necessary to minimize the use of global variables , Even if needed , We should also minimize its pollution .

1. using namespace std
var namespace1 = {
 a: function() {
   alert(1);
},
 b: function() {
   alert(2);
}
}
 Copy code 
Dynamically create namespaces
var MyApp = {};
​
MyApp.namespace = function( name ) {
 var parts = name.split('.');
 var current = MyApp;
 for( var i in parts) {
   if ( !current[ parts[i] ] ) {
     current[ parts[ i ]] = {}
  }
   current = current[ parts[ i ] ];
}
};
​
MyApp.namespace('event');
MyApp.namespace('dom.style');
​
console.dir( MyApp );
​
// The above code is equivalent to :
​
var MyApp = {
 event: {},
 dom: {
   style: {}
}
}
 Copy code 
2. Encapsulating private variables with closures
var user = (function() {
 var __name = 'sven',
     __age = 29;
 
 return {
   getUserInfo: function() {
     return __name + '-' + __age
  }
}
})
 Copy code 

Inertia alone

instance The instance object is always when we call Singleton.getInstance Was created when , Instead of creating... When the page is loaded , So we can implement an inert singleton .

Singleton.getInstance = (function() {
 var instance = null;
 return function( name ) {
   if ( !instance ) {
     instance = new Singleton( name );
  }
   return instance;
}
})
 Copy code 

Generic lazy singleton

var createIframe = (function() {
 var iframe;
 return function() {
   if (!iframe) {
     iframe = document.createElement('iframe');
     iframe.style.display = 'none';
     document.body.appendChild(iframe);
  }
   return iframe;
}
})
 Copy code 

Pull away

var getSingle = function(fn) {
 var result;
 return function() {
   return result || (result = fn.apply(this, arguments));
}
}
 Copy code 

Example

var createLoginLayer = function () {
 var div = document.createElement('div');
 div.innerHTML = ' I'm logging in to the float window ';
 div.style.display = 'none';
 document.body.appendChild(div);
}
​
var createSingleLoginLayer = getSingle(createLoginLayer);
​
document.getElementById('loginBtn').onClick = function() {
 var loginLayer = createSingleLoginLayer();
 loginLayer.style.display = 'block';
}
 Copy code 

Advantages and disadvantages of singleton mode

advantage :

  1. You can guarantee that there is only one instance of a class .
  2. You get a global access node to the instance .
  3. Initialize singleton objects only when they are first requested .

shortcoming :

  1. A violation of the Principle of single responsibility . This model solves two problems at the same time .
  2. Singleton patterns can mask bad design , For example, each component of the program knows too much about each other .
  3. Unit testing of singleton client code can be difficult , Because many test frameworks create mock objects in an inheritance based way . Because the constructor of the singleton class is private , And most languages can't override static methods , So you need to think of ways to simulate singletons carefully . Or don't write test code at all , Or don't use singleton mode .

official account @ Front end Growth Manual

版权声明
本文为[Cheng Huan x]所创,转载请带上原文链接,感谢
https://qdmana.com/2021/09/20210909122358638x.html

  1. Mid Autumn Festival special! Use the simplest animation animation to make the most local and trendy holiday blessing greeting card. This romantic male and female tears of Xiao Chen.
  2. Wang Ou went back to the hotel with the man at night. It was suspected that his relationship was open. The netizen replied mercilessly: is the man single
  3. 借助HTML ping属性实现数据上报
  4. APNG在线制作、兼容、播放和暂停
  5. Apng production, compatibilité, lecture et pause en ligne
  6. Mise en œuvre de l'escalade des données avec l'attribut de Ping HTML
  7. Comment envoyer 100 000 requêtes http le plus rapidement possible
  8. JQuery Basics
  9. Front and back end data interaction (V) -- what is Axios?
  10. Serverless is a model architecture invented driven by economic benefits- Grady
  11. Les questions d'entrevue pour les ingénieurs Java d'Internet, les intervieweurs rencontrés sont tous de niveau architecte,
  12. Cinq ans d'entrevue d'expérience en développement Java, découvrez les questions que vous devez poser lors de l'entrevue d'embauche du printemps Java de cette année.
  13. La dernière collection de questions d'entrevue Java haute fréquence organisée cette année, 2021 Java Universal Popular Framework
  14. Intel selected Weilai es8 to promote driverless taxis in Europe
  15. JavaScript operator (1), Web Development Engineer
  16. Trier les questions d'entrevue Javascript, trier les points de connaissance des itinéraires d'apprentissage
  17. Song Mengjun's "sleepless night" triggered an upsurge of dance storm after 00
  18. Module management of "free and open source" front-end spa project crudapi background management system based on Vue and Quasar (14)
  19. Encapsulated PHP sends HTTP requests with curl. Get and post are very easy to use
  20. Front and back end data interaction (V) -- what is Axios?
  21. Flutter: résoudre le futur blocage en utilisant Isolate
  22. Résumé des opérations courantes pour les données de structure de l'arbre frontal
  23. Ant Design Transfer Twin Tree Shuttle box "make Wheels"
  24. De la carte de pensée à la base et à l'approfondissement, prenez note de l'expérience d'entrevue d'un octet sautant le poste de recherche et développement Java.
  25. Apprenez les composants d'implémentation de vue et Publiez - les à NPM
  26. [Questions d'entrevue à haute fréquence] À vous de choisir
  27. Une faible connaissance de beginpath () provoque une superposition de style lors de la peinture d'un dessin en toile
  28. React Hooks, laisse - moi t'emmener étudier.
  29. Comment la copie profonde résout - elle les références circulaires?
  30. JavaScript Advanced Programming (3rd Edition) Reading note 6
  31. Analyse de l'URL
  32. Discussion préliminaire sur xss
  33. Solution: développement de la page Web Wechat, obtenir la fosse Piétinée par le flux d'entrée de la caméra via navigator.mediadevice.getusermedia ()
  34. Des milliers de questions d'entrevue sélectionnées n'ont pas encore ét é effacées.
  35. Les questions d'entrevue de niveau intermédiaire et avancé d'Android au fil des ans sont entièrement incluses, et l'algorithme est distribué microservice
  36. J'ai résumé toutes les questions d'entrevue.
  37. Compréhension de la réactivité des données de vue
  38. Note de service CSS (vi): Flex, page mobile et mise en page réactive
  39. Non-ASCII character ‘\xe5‘ in file kf1.py on line 4, but no encoding declared; see http://python.or
  40. 手把手教你搭建微信小程序服务器(HTTPS)
  41. JavaScript Review sketch - 1
  42. Analyse du bootstrap webpack
  43. sqli-labs-less-18 http头user agent+报错注入
  44. Génération de code nest pour l'outil CLI de nestjs
  45. JS | This
  46. Augmentation des variables
  47. The sinking gs8 raises its flag again. GAC motor's sales are falling endlessly. Is it the car or the people?
  48. Ren Hao's lunch at work today is president Hao wearing a sleeveless coat! Clean and handsome!
  49. Summary of basic knowledge points of JavaScript language (mind map)
  50. The new front-end lady asked: there was a 404 problem refreshing the page in Vue routing history mode
  51. Sqli Labs - less - 18 http header user agent + Error Reporting Injection
  52. Vous apprendrez à construire un serveur d'applet Wechat (https) à la main
  53. Non - ASCII character 'xe5' in file kf1.py on Line 4, but no Encoding declared;Voirhttp://python.or
  54. The new front-end lady asked: there was a 404 problem refreshing the page in Vue routing history mode
  55. En tant que programmeur, quelle est la plus grande tristesse que vous ressentez? L'entrevue d'emploi Java de 2021 dans une grande usine vous demandera:
  56. En tant que programmeur, je n'oublie pas le dernier résumé de mon expérience d'entrevue de stage en Java.
  57. Experts suggested that performers work with certificates, which triggered a collective heated debate. It is meaningless to be accused of repeating the mistakes
  58. The new front-end lady asked: there was a 404 problem refreshing the page in Vue routing history mode
  59. The appearance value of 200000 "Odyssey" is less than 100000, and has become the "sales champion" of household MPV
  60. Les programmeurs Java qui sont entrés dans l'entreprise pendant trois mois ont dû faire face à une correction d'échelle, et les octets ont sauté dans le traitement des questions d'entrevue de JD 360 Netease.