search
HomeWeb Front-endJS TutorialCommon design patterns in JS

Common design patterns in JS

Feb 23, 2018 pm 03:14 PM
javascriptCommonly usedDesign Patterns

In large-scale single-page applications, when the complexity rises to a certain level, there is no appropriate design pattern for decoupling, and subsequent development will be difficult to start.
The design pattern exists precisely for decoupling.

Singleton Mode

The core of the singleton mode is to ensure that there is only one instance and provide global access.

Features

Satisfies the "Single Responsibility Principle": Use the proxy mode, do not determine whether the singleton has been created in the constructor;

Satisfies the inertia principle

Application

The login window pops up.

Instance

 var getSingle = function (fn) {
    var res;
    return function() {
        return res || (res = fn.apply(this, arguments));
    }
}

var createPopup() {
    var p = document.createElement('p');
    p.innerHTML = "Login window";
    p.style.display = "none"; 
    document.body.appendChild(p);
    return p;
}

var createLoginPopup = getSingle(createPopup);            
//create popup p here by using a given function, 满足两个原则 

document.getElementById("loginBt").onclick = function() {
    var popup = createLoginPopup();
    pop.style.display = "block";
}

Constructor pattern

/**
 * 构造一个动物的函数 
 */
function Animal(name, color){
    this.name = name;
    this.color = color;
    this.getName = function(){
        return this.name;
    }
}
// 实例一个对象
var cat = new Animal('猫', '白色');
console.log( cat.getName() );

Prototype pattern

function Person(){  
}

Person.prototype.name = "bill";
Person.prototype.address = "GuangZhou";
Person.sayName = function (){
    alert(this.name);  
}

var person1 = new Person();
var person2 = new Person();
 
//测试代码
alert(person1.name);   // bill
alert(person2.name);    // bill
person1.sayName();    //bill
person2.sayName();    //bill

person1.name = "666";

alert(person1.name);   // 666
alert(person2.name);    // bill
person1.sayName();    //666
person2.sayName();    //bill

Mixed pattern

/**
 * 混合模式 = 原型模式 + 构造函数模式
 */
function Animal(name, color){
    this.name = name;
    this.color = color;

    console.log( this.name  +  this.color)
}
Animal.prototype.getInfo = function(){
    console.log('名称:'+ this.name);
}

function largeCat(name, color){
    Animal.call(null, name, color);

    this.color = color;
}

largeCat.prototype = create(Animal.prototype);
function create (parentObj){
    function F(){}
    F.prototype = parentObj;
    return new F();
};

largeCat.prototype.getColor = function(){
    return this.color;
}
var cat = new largeCat("Persian", "白色");
console.log( cat )

Factory pattern

Factory: The function generates the b object internally and returns it.

1. 
function a(name){
  var b = new object();
    b.name = name;
    b.say = function(){
        alert(this.name);
    }   
       return b    
}
2. 
function Animal(opts){
    var obj = new Object();
    obj.name = opts.name;
    obj.color = opts.color;
    obj.getInfo = function(){
        return '名称:'+obj.name +', 颜色:'+ obj.color;
    }
    return obj;
}
var cat = Animal({name: '波斯猫', color: '白色'});
cat.getInfo();

Simple Factory Pattern

The idea of ​​the simple factory pattern is to create objects and instantiate different classes; you only need to create an object, and then use a large number of methods and properties of this object, and In the end, the object is returned

//basketball base class  
var Baseketball = function(){  
  this.intro = 'baseketball is hotting at unitedstates';  
}  
Baseketball.prototype = {  
  getMember : function(){\  
    console.log('each team needs five players');  
  },  
  getBallSize : function(){  
    console.log('basketball is big');  
  }  
}  
//football base class   
var Football = function(){  
  this.intro = 'football is popular at all of the world';  
}  
Football = function(){  
  getMember = function(){  
  
  },  
  getBallSize = function(){  
  
  }  
}  
//sport factory  
var SportsFactory = function(name){  
  switch(name){  
    case 'NBA':  
      return new Baseketball();  
    case 'wordCup':  
      return new Football();  
  }  
}  
  
//when you want football   
var football = SportsFactory('wordCup');  
console.log(football);  
console.log(football.intro);  
football.getMember();

Iterator pattern

Decorator pattern

Strategy pattern

Define algorithms that can be replaced with each other, and They encapsulate.

Features

  1. Conforms to the open-closed principle: When you want to modify the algorithm used, you don’t need to go deep into the function to modify it, you only need to modify the strategy class;

  2. Separate the implementation and use of the algorithm to improve the reusability of the algorithm;

  3. Avoid multiple conditional selection statements through combination, delegation and polymorphism;

Apply

animation to achieve different easing effects.

Generally divided into two parts: strategy class and environment class. The strategy class is used to encapsulate various algorithms and is responsible for the specific calculation process; the environment class is responsible for receiving user requests and entrusting the requests to a certain strategy class. Because the algorithms and calculation results implemented by each strategy class are different, but the method of calling the strategy class by the environment class is the same, this reflects polymorphism. To implement different algorithms, you only need to replace the strategy class in the environment class.

In js, we do not have to construct a strategy class and can directly use functions as strategy objects.

Example

var strategies = {
    "s1": function() {
        //algo 1
    },
    "s2": function() {
        //algo 2
    }, 
    "s3": function() {
        //algo 3
    }
 }
 
 var someContext =  new SomeConext();
 someContext.start("s1");  //using s1 to calculate
 //someContext.add("s1");  or add s1 as a rule for validation

Appearance mode

can also be translated as facade mode. It provides a consistent interface for a set of interfaces in a subsystem. The Facade pattern defines a high-level interface that makes this subsystem easier to use. After the appearance role is introduced, the user only needs to interact directly with the appearance role. The complex relationship between the user and the subsystem is realized by the appearance role, thus reducing the coupling of the system.
For example, if you want to watch a movie at home, you need to turn on the stereo, then turn on the projector, then turn on the player, etc. After introducing the appearance character, you only need to call the "Open Movie Device" method. The appearance role encapsulates operations such as opening the projector, providing users with an easier-to-use method.

Function

  1. Simplify complex interfaces

  2. Decoupling and shielding users from direct access to subsystems

Example

In form, appearance mode looks like this in javascript:

function a(x){
   // do something
}
function b(y){
   // do something
}
function ab( x, y ){
    a(x);
    b(y);
}

The following is an example of blocking bubbling and blocking default events. When it comes to the role of appearance:

var N = window.N || {};

N.tools = {
    stopPropagation : function( e ){
        if( e.stopPropagation ){
            e.stopPropagation();
        }else{
            e.cancelBubble = true;
        }
    },

    preventDefault : function( e ){
        if( e.preventDefault ){
            e.preventDefault();
        }else{
            e.returnValue = false;
        }
    },
    
    stopEvent : function( e ){
        N.tools.stopPropagation( e );
        N.tools.preventDefault( e );
    }

The application of appearance mode in JavaScript can be mainly divided into two categories. A certain piece of code appears repeatedly. For example, the call of function a basically appears before the call of function b, so you can consider it. Wrap this code with appearance roles to optimize the structure. Another way is to place APIs that are incompatible with some browsers within the appearance for judgment. The best way to deal with these problems is to centralize all cross-browser differences into an appearance mode instance to provide an external interface.

Proxy mode

Definition of proxy mode: Provide a proxy for other objects to control access to this object. In some cases, one object is not suitable or cannot directly reference another object, and a proxy object can act as an intermediary between the client and the target object.

Virtual agent

Virtual agent delays the creation and execution of some expensive objects until they are really needed

Image lazy loading

//图片加载
let imageEle = (function(){
    let node = document.createElement('img');
    document.body.appendChild(node);
    return {
        setSrc:function(src){
            node.src = src;
        }
    }
})();

//代理对象
let proxy = (function(){
    let img = new Image();
    img.onload = function(){
        imageEle.setSrc(this.src);
    };
    return {
        setSrc:function(src){
            img.src = src;
            imageEle.setSrc('loading.gif');
        }
    }
})();

proxy.setSrc('example.png');

Merge http requests

If there is a function that requires frequent request operations, which is relatively expensive, you can collect request data over a period of time through a proxy function and issue it all at once

//上传请求
let upload = function(ids){
    $.ajax({
        data: {
            id:ids
        }
    })
}

//代理合并请求
let proxy = (function(){
    let cache = [],
        timer = null;
    return function(id){
        cache[cache.length] = id;
        if(timer) return false;
        timer = setTimeout(function(){
            upload(cache.join(','));
            clearTimeout(timer);
            timer = null;
            cache = [];
        },2000);
    }    
})();
// 绑定点击事件
let checkbox = document.getElementsByTagName( "input" );
for(var i= 0, c; c = checkbox[i++];){
    c.onclick = function(){
        if(this.checked === true){
            proxy(this.id);
        }
    }
}

Cache proxy

The cache proxy can provide temporary storage for some expensive operation results. During the next operation, if the parameters passed in are consistent with the previous ones, the previously stored operation results can be directly returned

//计算乘积
let mult = function(){
    let result = 1;
    for(let i = 0,len = arguments.length;i <h3 id="Advantages-and-Disadvantages">Advantages and Disadvantages</h3><p>1. Advantages: The proxy mode can separate the proxy object from the called object, reducing the coupling of the system. The proxy mode plays an intermediary role between the client and the target object, which can protect the target object. The proxy object can also perform other operations before calling the target object. <br>2. Disadvantages: Increases the complexity of the system</p><p>Observer mode</p><h2 id="Module-mode">Module mode</h2><pre class="brush:php;toolbar:false">/**
 * 模块模式 = 封装大部分代码,只暴露必需接口
 */
var Car = (function(){
    var name = '法拉利';
    function sayName(){
        console.log( name );
    }
    function getColor(name){
        console.log( name );
    }
    return {
        name: sayName,
        color: getColor
    }
})();
Car.name();
Car.color('红色');

Related recommendations:

JS combination design pattern detailed explanation

Detailed Explanation of the Service Locator Pattern Example of PHP Design Pattern

Detailed Explanation of the Delegation Pattern of PHP Design Pattern

The above is the detailed content of Common design patterns in JS. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft