JavaScript design pattern-single-entity (Singleton) pattern, javascript Design 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:
<! DOCTYPE html>
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
<! DOCTYPE html>
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
5. Other implementation methods
See visible blog: (http://www.cnblogs.com/TomXu/archive/2012/02/20/2352817.html)
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.