Learning about the JavaScript design pattern-the metadata pattern-javascript skills

Source: Internet
Author: User
This article mainly introduces the metadata-sharing mode in the JavaScript design mode. If you are interested in the JavaScript design mode, refer to it. I. Definition

The flyweight mode is a mode used for performance optimization. The core is to use the sharing technology to effectively support a large number of small scale objects.
In JavaScript, browsers, especially mobile browsers, do not allocate much memory. It makes sense to save memory.
The enjoy mode is an optimization mode that uses time for space.

  • The underwear factory has 100 kinds of men's underwear and 100 middle women's underwear, and requires photos of each kind of underwear. If you do not use the enjoy yuan model, you need 200 plastic models. If you use the enjoy yuan model, you only need one model for both men and women.

Ii. In what scenarios do I use the metadata sharing mode?

(1) A large number of similar objects are used in the program, resulting in high memory overhead.
(2) Most states of objects can be changed to external States. After the external States are stripped, a large number of objects can be replaced with a relatively small number of shared objects.

3. How to apply the metadata sharing mode?

The first is the application on the data layer, which is mainly applied to a large number of similar objects in the memory;
The second method is applied on the DOM layer. The metadata can be used in the central event manager to avoid attaching event handles to each child element in the parent container.

The object attribute must be dividedInternal statusAndExternal status.
The internal state is independent from the specific scenario and usually remains unchanged and can be shared by some objects;
The external status depends on the specific scenario and changes according to the scenario. The external status cannot be shared.

The factory mode is often used in the metadata mode. The internal state of Flyweight is used for sharing. The Flyweight factory is responsible for maintaining a Flyweight pool to store objects in the internal state.

Disadvantages:When the number of objects is small, the overhead of the system may be increased, and the implementation complexity is large!

Iv. Example: File Upload

Var Upload = function (uploadType) {this. uploadType = uploadType;}/* delete a file (internal state) */Upload. prototype. delFile = function (id) {uploadManger. setExternalState (id, this); // assemble the external States corresponding to the current id into the shared object. // if (this. fileSize <3000) {return this. dom. parentNode. removeChild (this. dom);} if (window. confirm ("are you sure you want to delete the file? "+ This. fileName) {return this. dom. parentNode. removeChild (this. dom) ;}}/** factory Object Instantiation * If a shared object in an internal state has been created, this object is directly returned * otherwise, create a new object */var UploadFactory = (function () {var createdFlyWeightObjs ={}; return {create: function (uploadType) {if (createdFlyWeightObjs [uploadType]) {return createdFlyWeightObjs [uploadType];} return createdFlyWeightObjs [uploadType] = new Upload (uploadType );}};})(); /* manager encapsulate external status */var uploadManger = (function () {var uploadDatabase ={}; return {add: function (id, uploadType, fileName, fileSize) {var flyWeightObj = UploadFactory. create (uploadType); var dom = document. createElement ('P'); dom. innerHTML = "file name:" + fileName + ", file size:" + fileSize + "" +"Delete"; Dom. querySelector (". delFile "). onclick = function () {flyWeightObj. delFile (id) ;}; document. body. appendChild (dom); uploadDatabase [id] = {fileName: fileName, fileSize: fileSize, dom: dom}; return flyWeightObj;}, setExternalState: function (id, flyWeightObj) {var uploadData = uploadDatabase [id]; for (var I in uploadData) {// directly change the parameter (new idea !!) FlyWeightObj [I] = uploadData [I] ;}};}) ();/* trigger upload action */var id = 0; window. startUpload = function (uploadType, files) {for (var I = 0, file; file = files [I ++];) {var uploadObj = uploadManger. add (++ id, uploadType, file. fileName, file. fileSize) ;}};/* test */startUpload ("plugin", [{fileName: '1.txt ', fileSize: 1000 },{ fileName: '2.txt', fileSize: 3000 }, {fileName: '3.txt ', fileSize: 5000}]); startUpload ("flash", [{fileName: '4.txt', fileSize: 1000}, {fileName: '5.txt ', fileSize: 3000 },{ fileName: '6.txt ', fileSize: 5000}]);

5. Supplement

(1) directly change the form parameter Demo

function f1() {  var obj = {a: 1};  f2(obj);  console.log(obj);  // {a: 1, b: 2}}function f2(obj) {  obj.b = 2;}f1();  

(2) Object pool,It is also a performance optimization solution, which has some similarities with the meta-mode, but does not separate the internal and external states.

var objectPoolFactory = function(createObjFn) {  var objectPool = [];  return {    create: function() {      var obj = objectPool.lenght === 0 ? createObjFn.apply(this, arguments) : objectPool.shift();      return obj;    },    recover: function() {      objectPool.push(obj);    }  };}

I hope this article will help you learn about javascript programming.

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.