_javascript Techniques for single case pattern instances of JavaScript design patterns

Source: Internet
Author: User

Peter Seibel, author of Practical Common Lisp, once said that if you need a pattern, there must be something wrong. The problem he said is that because of the innate defects of language, it is necessary to seek and summarize a common solution.

Either a weak type or a strong type, a static or dynamic language, an imperative or descriptive language, and each language has inherent advantages and disadvantages. A Jamaican athlete has some advantages in sprinting and even boxing, and lacks in yoga practice.

Warlocks and Shadow priests can easily be a great helper, and a hostile law that flies on a Macon map will be slightly embarrassed. In the program, the static language may need to spend a lot of effort to achieve the decorator, and JS because can at any time to throw methods to the object, so that the decorator pattern in JS became a chicken.

The JavaScript design mode of the book is still relatively few, "Pro JavaScript designs Patterns" is a more classic, but its examples are more verbose, so combined with the code I wrote in the work, my understanding summed up. If there is a deviation in my understanding, please do not hesitate to correct me.

One, single case mode

A singleton pattern is defined to produce a unique instance of a class, but JS itself is a "no class" language. Many talk about JS design mode of the article {} as a single example to use also barely make sense. Because JS generates objects in a variety of ways, let's look at another more meaningful single example.

There is a common need to click on a button to pop a mask layer on the page. For example, when web.qq.com clicks on login.

The code that generates the gray background mask layer is very well written.

Copy Code code as follows:

var createmask = function () {
Return Document,body.appendchild (document.createelement (div));
}
$ (' button '). Click (function () {
Var mask = Createmask ();
Mask.show ();
})

The problem is that the mask layer is globally unique, so each call to the createmask creates a new div, although it can be removed from the hidden mask layer. But obviously this is unreasonable.

Look at the second option, and create this div at the very beginning of the page. Then use a variable to refer to it.

Copy Code code as follows:

var mask = document.body.appendChild (document.createelement ("div"));
$ ("button"). Click (function () {
Mask.show ();
} )

This really creates a masking layer div on the page, but another problem comes along, maybe we'll never need the mask layer, and that's a waste of Div, and it should be very stingy with any manipulation of the DOM nodes.

If you can use a variable. To determine if a DIV has been created?

Copy Code code as follows:

var mask;
var createmask = function () {
if (mask) return mask;
else{
Mask = Document,body.appendchild (document.createelement (div));
return mask;
}
}

It looks good, so here it is. A function that produces a Single-column object. Let's take a closer look at what's wrong with this piece of code.

First of all, this function is a certain side effect, the function body changes the external variable mask reference, in many people collaboration project, Createmask is an unsafe function. On the other hand, mask this global variable is not necessarily necessary. Try to improve it.

Copy Code code as follows:

var createmask = function () {
var mask;
return function () {
return Mask | | (Mask = document.body.appendChild (document.createelement (' div '))
}
}()

Using a simple closure to wrap the variable mask, at least for the Createmask function, it is closed.

If you see this, you'll find that the single case pattern is too simple. Indeed, some design patterns are very simple, even if you have never paid attention to the concept of design patterns, in the usual code also unknowingly used a number of design patterns. Like years ago, when I realized what the old man's cart was, he thought about it.

The 23 design patterns in Gof are also patterns that have long existed and been reused in software development. If the programmer is not explicitly aware that he has used certain patterns, the next time he may miss a more appropriate design (this passage comes from the Sumbon world of programs).

Back to the point, the previous single case still has shortcomings. It can only be used to create a mask layer. What if I need to write a function to create a unique XHR object? Can you find a generic singleton wrapper.

In JS, functions are the first type, meaning that functions can also be passed as parameters. Look at the final code.

Copy Code code as follows:

var singleton = function (fn) {
var result;
return function () {
return Result | | (result = fn. Apply (this, arguments));
}
}
var createmask = singleton (function () {
Return Document.body.appendChild (document.createelement (' div '));
})

A variable is used to hold the return value for the first time, and if it has already been assigned, the variable will be returned preferentially in a subsequent call. The code that actually creates the mask layer is passed to the singleton wrapper by the way of the callback function. This approach is actually called bridging mode. About bridging mode, put it in the back a little bit.

The singleton function is not perfect, however, and it always requires a variable result to register the div reference. Unfortunately, the function of JS is not enough to complete the elimination of statements and statements.

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.