Understanding the design pattern in JavaScript

Source: Internet
Author: User
Introduction: reliable design patterns are the cornerstone of maintenance software. If you have been in a technical interview, you may be asked about design patterns. In the following guide, we will learn some design patterns that can be used today. What is the design model? Simply put, the design pattern is... syntaxHighlighter. all (); Introduction: reliable design patterns are the cornerstone of maintenance software. If you have been in a technical interview, you may be asked about design patterns. In the following guide, we will learn some design patterns that can be used today. What is the design model? Simply put, the design pattern is a software solution for reusing specific types of problems. These problems are often encountered during software development. Through years of practice, experts have summarized some methods for similar issues, which are encapsulated into a design model. Therefore, the model is a verified solution for solving software development problems. Patterns are scalable because they are often structured and you need to follow certain rules. For similar problems, patterns can be reused. In the next tutorial, we will provide some examples of design patterns. In software development, design patterns are generally divided into several categories. In this tutorial, we will focus on the following three types: 1. Creation patterns focus on building objects or classes, object creation sounds simple (in some cases), but large applications need to control the object creation process. 2. The structural design model focuses on the relationship between management objects so that applications can be scaled. The key aspect of the structural model is to ensure that some changes in the application do not affect other parts. 3. behavior patterns focus on communication between objects. You may still find that there is a problem after reading these descriptions. This is normal. Once we have read the in-depth introduction of these patterns, the problem will become clearer, so let's take a look. Class in JavaScript Note: When we read the design pattern, you often mention classes and objects. This is confusing because JavaScript does not have a true "class" structure. A more appropriate term is "data type ". Data Type in JavaScript: JavaScript is an object-oriented language. An object inherits from other objects. This concept is known as prototype inheritance. A data type can be created through the constructor, like: function Person (config) {this. name = config. name; this. age = config. age;} Person. prototype. getAge = function () {return this. age ;}; var tilo = new Person ({name: "Tilo", age: 23}); console. log (tilo. getAge (); when the method is defined in the Person data type, pay attention to the use of prototype. Because multiple Person objects will reference the same prototype, this allows getAge () this method can be shared by all Person-type instances. Instead of redefining each instance, any data type inherited from Person can access the getAge () method. Another common problem with processing private data in JavaScript is that there is no real private variable. However, we can use closures to simulate private variables. Consider the following code snippet: var retinaMacbook = (function () {// Private variables var RAM, addRAM; RAM = 4; // Private method addRAM = function (additionalRAM) {RAM + = additionalRAM ;}; return {// Public variables and methods USB: undefined, insertUSB: function (device) {this. USB = device ;}, removeUSB: function () {var device = this. USB; this. USB = undefi Ned; return device ;};}) (); In the above example, we created a retinaMacbook object that contains public and private variables and Methods. You can use it like this: retinaMacbook. insertUSB ("myUSB"); console. log (retinaMacbook. USB); // logs out "myUSB" console. log (retinaMacbook. RAM) // logs out undefined can do more in JavaScript Functions and closures, but we cannot cover all aspects in this tutorial, we briefly learned about JavaScript data types and private variables. Now we can learn the design model. Creation design patterns: there are many different creation design patterns, but here we will mainly discuss two types: Builder and Prototype ). Build mode: The build mode is usually used for web development. Sometimes you are using it but you are not aware of it. In short, this mode can be defined as follows: "using the build mode allows us to construct an object by specifying only the type and content, and we do not need to explicitly create the object ." For example, you may use jQuery: var myDiv =$ ('this is a div. '); // myDiv now represents a jQuery object referencing a DOM node. var someText = $ ('

'); // SomeText is a jQuery object referencing an HTMLParagraphElement var input = $ (' '); Let's take a look at the above three examples. The first one is to pass an element with some content, and the second one is to pass an empty

Tag, third, passElement. The results of these three examples are the same: return a reference of a jQuery object pointing to a DOM node. In jQuery, the $ variable adopts the construction mode. For example, the returned jQuery Dom object can access all the methods provided by the jQuery library, but the document is not displayed. createElement and JS libraries are usually processed in this advanced method. Imagine how much work to do. If we show that we create DOM elements and then insert the content into them. By using the construction mode, we can focus on the object type and content, rather than creating the display. Before the prototype mode, we discussed how to define a data type in the prototype of an object through functions and adding methods in JavaScript. In prototype mode, objects are allowed to inherit from other objects through prototype. "Prototype mode is a mode for cloning new objects based on existing template objects" in JavaScript, which is a simple and natural method for inheritance. For example: var Person = {numFeet: 2, numHeads: 1, numHands: 2}; // Object. create takes its first argument and applies it to the prototype of your new object. var tilo = Object. create (Person); console. log (tilo. numHeads); // outputs 1tilo. numHeads = 2; console. log (tilo. numHeads) // The outputs 2 attribute (method) applies the tilo object prototype to the Person object. We can redefine the attributes in the tilo object, if we want it to be different. In the above example, we use Object. create (), however, IE8 does not support this relatively new method. In this case, we can simulate its behavior: var vehiclePrototype = {init: function (carModel) {this. model = carModel;}, getModel: function () {console. log ("The model of this vehicle is" + this. model) ;}}; function vehicle (model) {function F () {}; F. prototype = vehiclePrototype; var f = new F (); f. init (model); return f;} var car = vehicle ("Ford Escort"); car. getModel (); unique The bad thing is that you cannot specify this method as a readable attribute, but you can specify it when using Object. create. In any case, the prototype mode shows how objects inherit from other objects. Structured mode: the structured design mode is very helpful when you want to understand a system if it works. It facilitates application expansion and maintenance. We will discuss the following two modes: The combination mode and the combination mode of the facade mode: The combination mode can be understood as the combination of an object can be processed in the same way as a single object. What does this mean? Well, consider the following example: $ ('. mylist '). addClass ('selected'); $ ('# myitem '). addClass ('selected'); // dont do this on large tables, it's just an example. $ ("# dataTable tbody tr "). on ("click", function (event) {alert ($ (this ). text () ;}); $ ('# myButton '). on ("click", function (event) {alert ("Clicked. ") ;}); many JavaScript libraries provide consistent APIs, whether processing a single DOM element or an array of DOM elements. We can add the selected class to all the elements that contain the. myList selector. Similarly, we can use the same method to process similar DOM elements # myItem. Similarly, we can use the on () method to attach an event processor to multiple nodes or a single node. Facade mode: hides complex internal structures and provides users with simple interfaces. The facade mode can almost always improve the availability of most software. Using jQuery as an example, ready (): $ (document) is the most popular method ). ready (function () {// all your code goes here ...}); the facade Mode Implemented by the ready () method. If you check the source code, you will find: ready: (function (){... // Mozilla, Opera, and Webkit if (document. addEventListener) {document. addEventListener ("DOMContentLoaded", idempotent_fn, false );...} // IE event model else if (document. attachEvent) {// ensure firing before onload; maybe late but safe also Iframes document. attachEvent ("onreadystatechange", idempotent_fn); // A fallback to window. onload, that will always work window. attachEvent ("onload", idempotent_fn );...}}) the ready () method is not simple. jQuery standardizes the consistency of the browser to ensure that ready () is triggered at the appropriate time. However, as a developer, you should use simple interfaces. Conclusion: The most encouraging thing about the design pattern is that someone has successfully practiced it in the past. Many open-source codes implement various JavaScript design patterns. As a programmer, we need to be aware of the application scenarios of each design pattern. I hope this tutorial can help answer these questions step by step.

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.