Deep understanding of the JavaScript series (37): The basic knowledge of the pattern of design

Source: Internet
Author: User

Introduced

Enjoy meta mode (Flyweight), run the sharing technology to effectively support a large number of fine-grained objects, avoid a large number of the same content of the small class of overhead (such as memory), so that everyone share a class (meta Class).

The element mode avoids the overhead of a large number of very similar classes, in the program design, sometimes need to produce a large number of fine-grained class instances to represent the data, if you can find these instances in addition to several parameters, the cost is basically the same, you can significantly less need to instantiate the number of classes. If you can move those parameters outside of the class instance and pass them in when the method is called, you can reduce the number of individual instances by sharing drastically.

So what if you apply the meta pattern in JavaScript? There are two ways of the first is applied to the data layer, mainly in the memory of a large number of similar objects; the second is applied to the DOM layer, which can be used on the central event manager to avoid attaching an event handle to each child element in the parent container.

The element and data layer

There are two important concepts in flyweight-internal state intrinsic and external state extrinsic, internal state is within the object through internal method management, and external information can be deleted or saved by the outside.

White point, is to pinch a first original model, and then with different occasions and environment, and then produce the specific characteristics of the model, it is obvious that here need to produce different new objects, so flyweight mode often appear Factory mode, flyweight internal state is used to share, Flyweight Factory is responsible for maintaining a Flyweight pool (pattern pool) to hold objects in the internal state.

Use the pattern of privileges

Let's demonstrate that if you let the system manage all the books through a class library, the metadata for each book is tentatively as follows:

Copy Code code as follows:

Id
Title
Author
Genre
Page Count
Publisher ID
Isbn

We also need to define the time of each book being loaned out and the borrower, as well as the date of retirement and the availability status:
Copy Code code as follows:

Checkoutdate
Checkoutmember
Duereturndate
Availability

Because the book object is set to the following code, note that the code has not been optimized:
Copy Code code as follows:

var book = function (ID, title, author, genre, Pagecount,publisherid, ISBN, Checkoutdate, Checkoutmember, Duereturndate,av ailability) {
This.id = ID;
This.title = title;
This.author = author;
This.genre = genre;
This.pagecount = PageCount;
This.publisherid = PublisherID;
This. ISBN = ISBN;
This.checkoutdate = checkoutdate;
This.checkoutmember = Checkoutmember;
This.duereturndate = duereturndate;
this.availability = availability;
};
Book.prototype = {
Gettitle:function () {
return this.title;
},
Getauthor:function () {
return this.author;
},
Getisbn:function () {
return this. ISBN;
},
/* Other Get methods are not shown here * *

Update the loan status
Updatecheckoutstatus:function (BookID, NewStatus, Checkoutdate,checkoutmember, newreturndate) {
This.id = BookID;
this.availability = NewStatus;
This.checkoutdate = checkoutdate;
This.checkoutmember = Checkoutmember;
This.duereturndate = newreturndate;
},
Renew
Extendcheckoutperiod:function (BookID, newreturndate) {
This.id = BookID;
This.duereturndate = newreturndate;
},
Whether to expire
Ispastdue:function (BookID) {
var currentdate = new Date ();
return Currentdate.gettime () > Date.parse (this.duereturndate);
}
};


The program may be fine at first, but as time increases, books can grow in large quantities, and each book has a different version and quantity, and you will find that the system is getting slower. Thousands of book objects can be imagined in memory, we need to use the element mode to optimize.

We can divide the data into internal and external data, and the book object related to the data (title, author, etc.) can be attributed to the internal properties, and (Checkoutmember, duereturndate, etc.) can be attributed to the external attribute. In this way, the following code can share the same object in the same book, because no matter who borrows the book, as long as the book is the same book, the basic information is the same:

Copy Code code as follows:

/* Enjoy meta mode optimized code * *
var book = function (title, author, genre, PageCount, PublisherID, ISBN) {
This.title = title;
This.author = author;
This.genre = genre;
This.pagecount = PageCount;
This.publisherid = PublisherID;
This. ISBN = ISBN;
};

Define a base factory

Let's define a base factory that checks to see if the book object was created before, and if it does, it returns without recreating and storing it so that you can continue to access it later, ensuring that we create only one object for each of these books:

Copy Code code as follows:

/* Book Factory single Case * *
var bookfactory = (function () {
var existingbooks = {};
return{
Createbook:function (title, author, GENRE,PAGECOUNT,PUBLISHERID,ISBN) {
/* Find whether to create * * before
var existingbook = EXISTINGBOOKS[ISBN];
if (Existingbook) {
return existingbook;
}else{
/* If not, create one, then save/*
var book = new book (title, author, Genre,pagecount,publisherid,isbn);
EXISTINGBOOKS[ISBN] = Book;
return book;
}
}
}
});

managing external states
External state, relatively simple, in addition to our packaged book, the others need to be managed here:
Copy Code code as follows:

/*bookrecordmanager Library Management type of single case * *
var Bookrecordmanager = (function () {
var bookrecorddatabase = {};
return{
* * Add a library record * *
Addbookrecord:function (ID, title, author, Genre,pagecount,publisherid,isbn, Checkoutdate, Checkoutmember, Duereturndate, availability) {
var book = Bookfactory.createbook (title, author, Genre,pagecount,publisherid,isbn);
Bookrecorddatabase[id] ={
Checkoutmember:checkoutmember,
Checkoutdate:checkoutdate,
Duereturndate:duereturndate,
Availability:availability,
Book:book;

};
},
Updatecheckoutstatus:function (BookID, NewStatus, Checkoutdate, Checkoutmember, newreturndate) {
var record = Bookrecorddatabase[bookid];
record.availability = NewStatus;
Record.checkoutdate = checkoutdate;
Record.checkoutmember = Checkoutmember;
Record.duereturndate = newreturndate;
},
Extendcheckoutperiod:function (BookID, newreturndate) {
Bookrecorddatabase[bookid].duereturndate = newreturndate;
},
Ispastdue:function (BookID) {
var currentdate = new Date ();
return Currentdate.gettime () > Date.parse (bookrecorddatabase[bookid].duereturndate);
}
};
});


In this way, we have been able to keep the same information of the same book in a Bookmanager object, and save only one copy, compared to the previous code, you can find that a lot of memory savings.

The privilege mode and DOM

About the DOM event bubbling, here is not much to say, I believe everyone already know, we give two examples.

Example 1: Centralized event management

For example, if we have many similar types of elements or structures (such as menus, or multiple Li in the UL) need to monitor his click events, it requires more than one element for the event binding, if the element has very much, that performance can be imagined, and the combination of bubbling knowledge, If any of the child elements have an event trigger, that triggers the event to bubble up to the upper level element, so using this feature, we can use the element pattern, we can monitor the parent elements of these similar elements, and then judge which child element has an event trigger, and then do further action.

Here we combine the Bind/unbind method of jquery to illustrate.

Html:

Copy Code code as follows:

<div id= "Container" >
<div class= "Toggle" href= "#" > More information (address)
<span class= "Info" >
Here are more information
</span></div>
<div class= "Toggle" href= "#" > More information (map)
<span class= "Info" >
<iframe src= "http://www.map-generator.net/extmap.php?name=London&address=london%2C%20england&width= 500...gt; " </iframe>
</span>
</div>
</div>

Javascript:
Copy Code code as follows:

Statemanager = {
Fly:function () {
var self = this;
$ (' #container '). Unbind (). bind ("click", Function (e) {
var target = $ (E.originaltarget | | e.srcelement);
Determine which child element
if (target.is ("Div.toggle")) {
Self.handleclick (target);
}
});
},

Handleclick:function (elem) {
Elem.find (' span '). Toggle (' slow ');
}
});

Example 2: Using the meta mode to promote performance

Another example, still associated with jquery, is that when we use the element object in the callback function of the event, we will often use the $ (this) form, in fact it repeats the creation of the new object, because this is already the DOM element itself in the callback function. We need to use code such as the following:

Copy Code code as follows:

$ (' div '). bind (' click ', function () {
Console.log (' Your clicked: ' + $ (this). attr (' id '));
});
The above code, to avoid using, to avoid the DOM element to generate a jquery object, because it can directly use the DOM element itself.
$ (' div '). bind (' click ', function () {
Console.log (' You clicked: ' + this.id);
});

In fact, if you want to use the form of $ (this), we can also implement our own version of Single-instance mode, such as we implement a jquery.signle (this) function to return the DOM element itself:
Copy Code code as follows:

Jquery.single = (function (o) {

var collection = JQuery ([1]);
return function (Element) {

Put the elements in the collection
Collection[0] = element;

Return collection
return collection;

};
});


How to use:
Copy Code code as follows:

$ (' div '). bind (' click ', function () {
var html = jquery.single (this). Next (). HTML ();
Console.log (HTML);
});

In this way, the DOM element itself is returned as it is, and the jquery object is not created.

Summarize

Flyweight mode is a model that improves program efficiency and performance, and can greatly speed up the program. Many applications: For example, if you are reading a series of strings from a database, many of which are duplicates, then we can store these strings in the flyweight pool ( Pool).

If an application uses a large number of objects, and these lots of objects create a lot of storage when you're happy, you should consider using the meta mode; Most of the object's state can be external, and if you delete the external state of the object, you can replace many groups of objects with a relatively small number of shared objects. You can consider the use of the pattern of the privilege at this time.

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.