Javascript Design Pattern

Keywords: Javascript JQuery React Vue

Design principles (SOLID)

Single responsibility model

Principle of lie substitution

Open and closed principle

Interface isolation principle

Principle of Dependence Inversion

Design pattern

Factory mode

  • Encapsulate the new operation separately
  • When encountering new, consider whether to use factory mode

Example

You go to buy hamburgers, order and take the meals directly, but you don't make them by yourself
Stores should "package" hamburgers and give them directly to buyers

UML class diagram:

Code example:

class Product {
    constructor(name) {
        this.name = name;
    }
    init() {
        console.log('init')
    }
    fn1() {
        console.log('fn1')
    }
    fn2() {
        console.log('fn2')
    }
}

class Creator {
    create(name) {
        return new Product(name)
    }
}

let create = new Creator();
let p = create.create('p')
p.init()
p.fn1()
p.fn2()

Application scenario

1,jQuery:

What's the difference between $('div ') and new $('div')?

  • First, writing is troublesome, jQuery's chain operation will become a nightmare
  • Second: once the jQuery name changes, it will be disastrous
//jQuery like code
class jQuery {
    constructor(selector) {
        let slice = Array.prototype.slice;
        let dom = slice.call(document.querySelectorAll(selector))
        let len = dom ? dom.length : 0
        for (let i = 0; i < len; i++) {
            this[i] = dom[i]
        }
        this.length = len
        this.selector = selector || ''
    }
    append() {
        console.log('append');
    }
    addClass() {
        console.log('addClass')
    }

}

window.$ = function(selector) {
    return new jQuery(selector);
}

var $p = $('p')
console.log($p)
console.log($p.addClass)

2,React.crateElement:

var profile = <div>
    <img src="avater.png" className="profile"/>
    <h3>{[user.firstName,user.lastName].join('')}</h3>
    </div>;

After compilation:

var profile = React.createElement("div",null,
    React.createElement("img",{src:"avater.png",className:"profile"}),
    React.createElement("h3",null,[user.firstName,user.lastName].join(" "))
);
//Source code implementation
class vnode(tag, attrs, children) {
    //... omit internal code
}

React.createElement = function(tag,attrs,children){
    return new vnode(tag,attrs,children)
}

3. Asynchronous components of Vue:

Vue.component('async-example', funciton(resolve, reject) {
    setTimeout(function() => {
        resolve({
            template: '<div>I am async!</div>'
        })
    }, 1000);
})

Verification of design principles:

  • Separation of constructor and creator
  • Conform to the principle of opening and closing

Singleton mode

  • Only used in the system
  • There is only one instance in a class

 

Example:

Login box, shopping cart

Code demo

Demonstration of java version's singleton pattern

public class SingleObject{
     //Note: privatization constructor, external cannot be new, only internal NEW!!!!
     private SingleObject(){}
     //The only new object
     private SingleObject getInstance(){
         if(instance == null){
             //Only new once.
             instance = new SingleObject();
         }
         return instance;
     }
     //Object method
     public void login(username,password){
         System.out.println("login...")
     }
 }
 
 
 public class SingletonPatternDemo{
     public static void main(String[] args){
        //Illegal constructor
        //Compilation error: constructor SingleObject() is invisible!!!
        //SingleObject object = new SingleObject();
        //Get the only available objects
        SingleObject object = SingleObject.getInstance();
     }     
}

The demonstration of Javascript's single mode

class SingleObject {
    login() {
        console.log('login...')
    }
}

//Static method
SingleObject.getInstance = (function() {
    let instance
    return function() {
        if (!instance) {
            instance = new SingleObject();
        }
        return instance;
    }
})()

var login = SingleObject.getInstance().login();

Disadvantages of javascript's singleton mode:

If you force new, you will not report an error:

var loginnew = new SingleObject();
loginnew.login()

Test:

//Note that only static function getInstance can be used here, not new SingleObject()!!!
let obj1 = SingleObject.getInstance()
obj1.login()
let obj2 = SingleObject.getInstance()
obj2.login()
console.log(obj1 === obj2); //Both must be exactly the same

Adapter mode

Decorator mode

proxy pattern

Appearance mode

Observer mode

Iterator mode

State mode

To be continued, updated daily

Posted by JoelRocks on Mon, 09 Dec 2019 14:44:23 -0800