Singleton mode, also list example mode. As the name implies, it is a class that can only be instantiated once (there is no real class in JavaScript, we usually use a function to emulate a class, which is customary to call "pseudo-class"). Specifically, the singleton pattern, in the case where the instance does not exist, can be used to create a new instance of the class by means of a method that can be created, and if the instance already exists, it returns a reference to that object.
Next I'll use a case column to analyze the singleton pattern. In our web site, we will usually see some images zoomed in to view, such as:
When my mouse touches the figure of the handsome guy, it will appear a magnified icon (here the magnifying icon is a bit strange = =!) ), so we click on this screen will appear such as:
Yes, when you zoom in, you can see the handsome hosting. This is the example that I have brought to you, now we analyze the JS used: (HTML,CSS partial ignore)
First we write event functions that are compatible with each version of the browser (refer to the Events section of JavaScript Advanced programming): This example only uses the adds function in Eventutil.
var eventutil = {adds:function (element,type,func) {if ( Element.addeventlistener) {Element.addeventlistener (type,func,false);} else if (element.attachevent) {element.attachevent ("on" +type,func);} else{element["on" +type] = func;}},removes:function (element,type,func) {if (Element.removeeventlistener) { Element.removeeventlistener (Type,func,false);} else if (element.detachevent) {element.detachevent ("on" +type,func);} else{element["on" +type] = Null;}},getevent:function (event) {return event? Event:window.event;},gettarget:function (E Vent) {return Event.target | | event.srcelement;},preventdefault:function (event) {if (Event.preventdefault) { Event.preventdefault ();} Else{event.returnvalue = False;}},stoppropagation:function (event) {if (event.stoppropagation) { Event.stoppropagation ();} Else{event.cancelbubble = True;}}
}function $ (ID) {return typeof id = = = "string"? document.getElementById (ID): ID;}
The next step is to design this amplification feature. First you'll think that since I'm going to zoom in, I'm definitely going to have to enlarge the picture and enlarge the container that the picture is filled with. Yes, we're going to create these with a series of DOM methods that we'll see later.
When we enlarge the image every time there is a place that will not change, is the background shadow and the container to put pictures. Each time it is a background div and a picture-holding Div object is displayed in our browser and then closed. The specific analysis is that this object can be unique, I just need to save it in the cache, zoom in when the object is loaded into our page by the Document.body.appendChild () method, and then use RemoveChild () when closing method to remove it from the page (not removed from the cache), how do we guarantee that each call to this object is the first time the object is called? (This may be a bit complicated, and brevity is the invocation of the original object every time).
This time singleton mode can be a good solution to this problem. Back to just all of the saved in the cache, we are familiar with JS and other high-level language garbage collection mechanism, it uses reference counting method (refer to the JavaScript Advanced Programming chapter fourth) for memory management. Since we need this object to always be unique, we need to keep the object in the cache, that is, otherwise it will be recycled, so how do we do it?
Closures. Yes, we can use closures (the singleton model builds dependency closures, this concept is not mentioned). So we can take the following methods to achieve:
var Showbig = (function () {var listen; Reference function initial () {var listen_2,listen_3 as object, function Createbgshadow () {//Do not consider the code here}function Createbgcenterdiv () {///do not consider the code here}return{create:function () {///first do not consider the code here},removes:function () {///do not consider the code}}}return{getshadow here: function () {if (!listen) { //) If Listen does not refer to this object, the initial method is called once. If referenced, skip directly over listen = initial ();} return listen; Return this object (or the object's Reference)},getpic:function (Picurl) {///first not considering the code here}}) ();
as you can see in the code above, in order to save the object I want to keep in memory, I used a listen as my listener (I personally call it a reference to this object). Because listen is in a closure environment, when the initial () method is returned for the first time, listen always comes with the object returned by the initial () method, and when the second or later call is made again, listen does not disappear from memory, so it directly returns the listen in memory.
And what we're going to return is a background shadow object that we can do:
function Createbgshadow () { //shadow background creation var SHADOWBG = document.createelement ("div"); Shadowbg.setattribute ("id", " Picshadow "); return SHADOWBG; }function Createbgcenterdiv () { //The creation of a container for a picture is var shadowbgcenterdiv = document.createelement ("div"); Shadowbgcenterdiv.setattribute ("id", "realdiv");//The creation of the image after magnification var shadowbgcenterpic = document.createelement ("img"); Shadowbgcenterpic.setattribute ("src", "" "); Shadowbgcenterpic.setattribute (" id "," realpic "); Shadowbgcenterdiv.appendchild (shadowbgcenterpic);//Cancel the enlarged picture (that x) by creating var Cancel = document.createelement ("img"); Cancel.setattribute ("id", "cancelpic"); Cancel.setattribute ("src", "img/cancel.png"); Shadowbgcenterdiv.appendchild (cancel); return shadowbgcenterdiv;} Note that they all return a DOM node object. This step is critical.
The two objects are then saved in Listen_2,listen_3, as well as in memory, as are the initial (). So we can do this:
return{ //create () method joins a node to an HTML page create:function () {if (!listen_2 | |!listen_3) { //listen2 the node that holds the shadow background listen_2 = Createbgshadow (); Listen3 Save the picture and the node of the picture container listen_3 = Createbgcenterdiv ();} Since Listen_2 and listen_3 also use closures, they are always stored in memory, where objects are created only once Document.body.appendChild (listen_2);d Ocument.body.appendChild ( Listen_3);}, the //removes () method moves the node out of the HTML page removes:function () {var Picshadow = $ ("Picshadow"); var Realdiv = $ ("Realdiv" );d Ocument.body.removeChild (Picshadow);d ocument.body.removeChild (Realdiv);}}
This time it is clear what the singleton mode does, and it avoids creating duplicate objects multiple times, creating objects that we can use repeatedly. We use Listen,listen_2,listen_3 to preserve these objects that we need to use over and over again. Singleton mode uses closures to create the applications we need more quickly, but these objects are also kept in our memory, so the singleton pattern has its own scope of application, highlighting a "single" word.
Simply summarize the singleton mode:
1.singleton mode is one of the most basic and useful patterns of JavaScript, which provides a means of organizing code into a logical unit that is accessed through a single variable. (Accessed through a single interface, here is the Create () interface in the first singleton and the Getshadow () interface in the second singleton)
2.singleton mode can be used to partition namespaces to reduce the flooding of global variables. (We just used a showbig global variable)
The 3.singleton mode repeatedly references the same object in memory through JS's closure feature, which enables faster execution of the application.
The disadvantage of 4.singleton mode is that it provides a single point of access that can lead to strong coupling between modules (our program adheres to the principle of high cohesion and low coupling). This scenario should be taken into account when choosing this pattern. Not all situations should be chosen, but analyzed first.
The complete code is as follows (do not forget to modify the URL of the image when testing):
<! DOCTYPE html>
Analysis and application of singleton mode in JS