JavaScript design pattern (i) single case mode, combination mode and appearance mode __java

Source: Internet
Author: User

author Joseph Zimmerman http://www.joezimjs.com Date Created

March 2012


This article is the first of a series of articles that describe the common design patterns used by JavaScript. Design patterns are reliable programming methods that help ensure that your code is easier to maintain, expand, and detach, and that all design patterns are essential when creating large JavaScript applications, especially in large groups. Single case Mode

The singleton pattern refers to the design pattern that is used when you want to ensure that only one object instance is always created. In object-oriented classical programming languages, the concept behind the creation of a single case pattern is somewhat incomprehensible, because it contains a class that has both static and Non-static properties and methods. This article focuses on JavaScript, therefore, because JavaScript is a dynamic language that does not contain a real class, the JavaScript version of the single example pattern is extremely simple. Why you need to use a single case pattern.

Before I begin to introduce implementation details, I need to explore why a single example pattern is useful for applications. It ensures that you have only one object instance that can actually be useful. In a server-side language, you might use a single example to process a database connection because creating multiple database connections for a request is a waste of resources. Similarly, in front-end JavaScript, you might want to set an object that handles all AJAX requests to a single instance. The rule is simple: if the function of the instance is exactly the same each time a new instance is created, it is set to a single example.

However, this is not the only reason to adopt a single example. In JavaScript at least, a single example allows you to keep namespace objects and functions in order, preventing them from being confused with the global namespace, and you may understand that this is a scary idea, especially if you are using Third-party code. Using a namespace single case pattern is also called a module design pattern. Show single case mode

To create a single instance, you only need to create an object literal.

var Singleton = {
    prop:1,
    another_prop: ' Value ',
    method:function () {...},
    another_method:function () {... }
};

You can also create a single instance with private properties and methods, but it is somewhat difficult to understand because it involves the use of closed functions and the invocation of anonymous functions. Some local functions and/or variables are declared inside the function. Then, you create and return an object literal that contains methods that reference variables and functions that you declare in a larger range of functions. Immediately after the function declaration is placed () the external function is executed and the resulting object text is assigned to the variable. If these introductions are confusing to you, look at the code below and I'll make a further explanation later.

var Singleton = (function () {
    var private_property = 0,
        private_method = function () {
            Console.log (' This is PR Ivate ');
        }
    
    return {
        prop:1,
        another_prop: ' Value ',
        method:function () {
            private_method ();
            Return Private_property
        },
        another_method:function () {...}}
    }
());

The key is that when the variable is declared through Var, which is in front of the function that contains the variable, it can only be accessed within the function through functions declared within the function, such as functions within the object literal. The return statement helps us to go back to the object text that is assigned to a single instance after the external function executes itself. single Case schema namespace

In JavaScript, namespaces are done by adding an object as a property of another object, so the depth is one or more layers. This is useful for combining code into logical fragments. Although I think YUI JavaScript library to some extent namespace hierarchy is too many, but overall still can be counted as the nested namespace limited to a few or fewer layers of best practices. The following code is an example of a namespace.

var Namespace = {
    Util: {
        util_method1:function () {...},
        util_method2:function () {...}}
    ,
    Ajax: {
        Ajax_method:function () {...}}
    ,
    some_method:function () {...}}
;

Here's what it looks like it ' s used
Namespace.Util.util_method1 ();
Namespace.Ajax.ajax_method ();
Namespace.some_method ();

As mentioned earlier, using namespaces guarantees the lowest number of global variables. You can even connect an entire application to a single object namespace-named application, if you have this privilege. If you would like to continue to learn more about the applicability of the single design pattern and its namespace, continue to learn to view the article "JavaScript design mode: Single case mode" on my personal blog. Combination Mode

If you think "Hi, this is easy" after you read through the single example mode, then don't worry, I have some more complex patterns to discuss, one of which is the combination mode. A combination, as the name suggests, means creating a single entity with an object that contains more than one part. This single entity will serve as an access point for all of these parts, although this greatly simplifies the operation, but it can also be quite deceptive, since there is no implicit way of clearly indicating how many parts the combination contains. Composite Structure

We'd better use a combination of illustrative explanations. In Figure 1, you can see two different types of objects: containers and libraries are combined, and images are blades. Combinations can host children, but generally do not implement more behavior. Blades contain most of the behavior, but cannot host children, at least not in the traditional combinatorial example.


Figure 1. Composite structure

Another example, I'm personally sure you've seen the combo pattern before, but never really thought deeply. The computer file structure is an example of a combination pattern. If you delete a folder, all the contents of that folder will also be deleted, right? This is essentially the operation principle of combinatorial mode. You can invoke higher-level grouped objects on the structure tree, and messages will be transferred down this hierarchy. Combined Encoding Example

This example creates a picture library as an example of a combined pattern. There are only three levels: albums, libraries, and images. Albums and libraries will be grouped and the image is blades, as shown in Figure 1. This is a structure that is more specific than the requirements of the composition itself, but for this example it is meaningful to limit these levels to combinations or blades. The standard combination does not limit which structural layers can have blades or limit the number of blades.

To begin, you should first create the Gallerycomposite "class" for albums and libraries. Note that I am using JQuery to perform DOM operations to simplify the process.

var gallerycomposite = function (heading, id) {this.children = [];  This.element = $ (' <div id= ' + ID + ' "class=" Composite-gallery "></div>"). Append ('  

This position is a bit tricky, can you allow me to explain more. We use the Add, remove, and Getchild methods to build this combination. This example does not actually use remove and getchild, but they are useful for creating dynamic combinations. The hide, show, and GetElement methods are used to manipulate the DOM. This combination is intended to be presented to the user on the page as a representation of the library. This combination allows you to control these library elements through hide and show. If you call Hide on an album, the entire album disappears, or you can only raise it on a single image so that only the image disappears.

Now, create a Galleryimage class. Note that it uses exactly the same method as Gallerycomposite. In other words, they implement the same interface, but the image is a blade, so no action is actually performed on the child-related method, as if it had no subkeys. The combination must be run with the same interface because the composite element does not know if it is adding another composite element or a blade, so if you try to raise these methods on its subkeys, you need to run completely normal without any errors.

var galleryimage = function (src, id) {
    this.children = [];

    This.element = $ ('  ')
    . attr (' ID ', id)
    . attr (' src ', src);
}

Galleryimage.prototype = {
    //Due to this being a leaf, it doesn ' t use these methods,
    //But must implement them t O count as implementing the
    //Composite Interface
    Add:function () {},

    remove:function () {},

    Getchi Ld:function () {},

    hide:function () {
        this.element.hide (0);
    },

    show:function () {
        This.element.show (0);
    },

    getelement:function () {return
        this.element
    }
}


Since you have built the object prototype, you are now able to use it. From below you can see the code that actually constructs the image library.


var container = new Gallerycomposite (', ' allgalleries ');
var gallery1 = new Gallerycomposite (' Gallery 1 ', ' gallery1 ');
var gallery2 = new Gallerycomposite (' Gallery 2 ', ' Gallery2 ');
var image1 = new Galleryimage (' image1.jpg ', ' img1 ');
var image2 = new Galleryimage (' image2.jpg ', ' img2 ');
var image3 = new Galleryimage (' image3.jpg ', ' img3 ');
var image4 = new Galleryimage (' image4.jpg ', ' img4 ');

Gallery1.add (image1);
Gallery1.add (image2);

Gallery2.add (image3);
Gallery2.add (image4);

Container.add (gallery1);
Container.add (Gallery2);

Make sure to add "Top container" to "body,
//Otherwise it ' ll never show up.
Container.getelement (). Appendto (' body ');
Container.show ();

This is all the code for the combination. If you want to see a live demo of the library, you can visit the demo page on my blog. You can also read more about this pattern in the article "JavaScript design mode: Combination mode" on my blog. appearance mode

The appearance pattern is the last design pattern described in this article, which is simply a function or another piece of code that simplifies a complex interface. In fact, this pattern is quite common, and one might say that most functions are actually intended to do this. The goal of the skin pattern is to simplify the large logical fragment into a simple function invocation operation. Sample Appearance Patterns

You may have been using the skin pattern, but you don't think you're using any design patterns. The image Library of almost any programming language you use uses the appearance pattern to some extent, because their general purpose is to make complex transactions simpler.

Let's look at a jquery example, jquery uses a function (jquery ()) to perform multiple operations, it can query the DOM, create elements, or simply convert DOM elements to jQuery objects. If you just want to know about DOM queries and simply look at the number of lines of code that are used to create the feature, you might say to yourself, "I'm glad I don't have to write this code," because the code is too long and complex. For your convenience, they have successfully converted hundreds of of lines of complex code into a simple function call using the skin pattern. Concluding remarks

The appearance pattern is easy to understand, but if you are interested, you can read my personal blog JavaScript design pattern: Look at the text for more information.
Next Study Direction

In this part of the JavaScript design pattern series, I introduced the single case pattern, the combination mode, and the appearance pattern, and then in the second part of the series, I'll introduce you to another 3 design patterns, some of which are more complex than the concepts involved here. If you are not patient enough, I have written a series of JavaScript design patterns on my personal blog, including several design patterns that I do not intend to cover in this series of articles. You can find all the articles in the series on my blog.

Related Article

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.