Table of Contents
Singleton Mode
Features
Application
Instance
Constructor pattern
Prototype pattern
Mixed pattern
Factory pattern
Simple Factory Pattern
Iterator pattern
Strategy pattern
Apply
Appearance mode
Function
Example
Proxy mode
Virtual agent
Image lazy loading
Merge http requests
Cache proxy
Advantages and Disadvantages
Module mode
Home Web Front-end JS Tutorial Common design patterns in JS

Common design patterns in JS

Feb 23, 2018 pm 03:14 PM
javascript Commonly used Design 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";
}
Copy after login

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() );
Copy after login

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
Copy after login

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 )
Copy after login

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();
Copy after login

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();
Copy after login

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
Copy after login

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);
}
Copy after login

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 );
    }
Copy after login

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');
Copy after login

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);
        }
    }
}
Copy after login

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 < len;i++){
        result*= arguments[i];
    }
    return result;
}

//缓存代理
let proxy = (function(){
    let cache = {};
    reutrn function(){
        let args = Array.prototype.join.call(arguments,',');
        if(args in cache){
            return cache[args];
        }
        return cache[args] = mult.apply(this,arguments);
    }
})();
Copy after login

Advantages and Disadvantages

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.
2. Disadvantages: Increases the complexity of the system

Observer mode

Module mode

/**
 * 模块模式 = 封装大部分代码,只暴露必需接口
 */
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('红色');
Copy after login

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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The difference between design patterns and architectural patterns in Java framework The difference between design patterns and architectural patterns in Java framework Jun 02, 2024 pm 12:59 PM

In the Java framework, the difference between design patterns and architectural patterns is that design patterns define abstract solutions to common problems in software design, focusing on the interaction between classes and objects, such as factory patterns. Architectural patterns define the relationship between system structures and modules, focusing on the organization and interaction of system components, such as layered architecture.

Analysis of the Decorator Pattern in Java Design Patterns Analysis of the Decorator Pattern in Java Design Patterns May 09, 2024 pm 03:12 PM

The decorator pattern is a structural design pattern that allows dynamic addition of object functionality without modifying the original class. It is implemented through the collaboration of abstract components, concrete components, abstract decorators and concrete decorators, and can flexibly expand class functions to meet changing needs. In this example, milk and mocha decorators are added to Espresso for a total price of $2.29, demonstrating the power of the decorator pattern in dynamically modifying the behavior of objects.

PHP design pattern practical case analysis PHP design pattern practical case analysis May 08, 2024 am 08:09 AM

1. Factory pattern: Separate object creation and business logic, and create objects of specified types through factory classes. 2. Observer pattern: allows subject objects to notify observer objects of their state changes, achieving loose coupling and observer pattern.

How design patterns deal with code maintenance challenges How design patterns deal with code maintenance challenges May 09, 2024 pm 12:45 PM

Design patterns solve code maintenance challenges by providing reusable and extensible solutions: Observer Pattern: Allows objects to subscribe to events and receive notifications when they occur. Factory Pattern: Provides a centralized way to create objects without relying on concrete classes. Singleton pattern: ensures that a class has only one instance, which is used to create globally accessible objects.

The wonderful use of the adapter pattern in Java design patterns The wonderful use of the adapter pattern in Java design patterns May 09, 2024 pm 12:54 PM

The Adapter pattern is a structural design pattern that allows incompatible objects to work together. It converts one interface into another so that the objects can interact smoothly. The object adapter implements the adapter pattern by creating an adapter object containing the adapted object and implementing the target interface. In a practical case, through the adapter mode, the client (such as MediaPlayer) can play advanced format media (such as VLC), although it itself only supports ordinary media formats (such as MP3).

PHP Design Patterns: Test Driven Development in Practice PHP Design Patterns: Test Driven Development in Practice Jun 03, 2024 pm 02:14 PM

TDD is used to write high-quality PHP code. The steps include: writing test cases, describing the expected functionality and making them fail. Write code so that only the test cases pass without excessive optimization or detailed design. After the test cases pass, optimize and refactor the code to improve readability, maintainability, and scalability.

Application of design patterns in Guice framework Application of design patterns in Guice framework Jun 02, 2024 pm 10:49 PM

The Guice framework applies a number of design patterns, including: Singleton pattern: ensuring that a class has only one instance through the @Singleton annotation. Factory method pattern: Create a factory method through the @Provides annotation and obtain the object instance during dependency injection. Strategy mode: Encapsulate the algorithm into different strategy classes and specify the specific strategy through the @Named annotation.

What are the advantages and disadvantages of using design patterns in java framework? What are the advantages and disadvantages of using design patterns in java framework? Jun 01, 2024 pm 02:13 PM

The advantages of using design patterns in Java frameworks include: enhanced code readability, maintainability, and scalability. Disadvantages include complexity, performance overhead, and steep learning curve due to overuse. Practical case: Proxy mode is used to lazy load objects. Use design patterns wisely to take advantage of their advantages and minimize their disadvantages.

See all articles