We learn the steps of design pattern should be to first understand the idea, rational use of design pattern, summing up experience, mastery.

Publish and subscribe model

A one-to-many dependency between objects in which all other dependent objects are notified when one object changes state.

We can understand it in terms of multi-level linkage modules that select provinces, cities, counties and districts.

 // Publish subscribe mode
    class Pubsub{
        constructor() {
            this.subsrcibers = {};
        }
        / / subscribe
        subscribe(type,fn) {
            let listeners = this.subsrcibers[type] || [];
            listeners.push(fn);
        }
        // Unsubscribe
        unsubscribe(type,fn) {
            let listeners = this.subsrcibers[type];
            if(! listeners || ! listeners.length)return;
            this.subsrcibers[type] = listeners.filter((v) = >v ! == fn); }// Touch the subscription event
        publish(type,... args){
            let listeners = this.subsrcibers[type];
            if(! listeners || ! listeners.length)return;
            listeners.forEach((fn) = > fn(...args));
        }
    }
    let ob = new Pubsub();
    ob.subscribe("add".(val) = > console.log(val));
    ob.publish("add".1);
Copy the code

Command mode

Command Pattern is a kind of data-driven design Pattern, which belongs to behavior Pattern. The request is wrapped in the object as a command and passed to the calling object. The calling object looks for a suitable object that can handle the command and passes the command to the corresponding object, which executes the command.

We’re encapsulating a request as an object, sending different requests and parameters, and letting it perform its function, and the benefit of that is decoupling.

   // Command mode

    // Set the command
  
            const setCommand = (button,command) = >{
            button.onclick = () = >{ command.execute(); }}// Write the business logic here
        const MenuBar = {
            refresh: () = > {
                console.log("refresh"."jackson"); }}const RefreshMenBarCommand = (receiver) = >{
            return{
                execute: () = >{ receiver.refresh(); }}}const refreshMenBarCommand = new RefreshMenBarCommand(MenuBar);
        // Set binding buttons and directives
        setCommand(refreshButton,refreshMenBarCommand);
Copy the code

Portfolio model

Using small objects to construct a larger object is to combine a number of small objects into a larger object, which is equivalent to adding branches to a tree trunk. It is generally used to represent a part -> whole hierarchy. From is – a to has – a

 // Combination mode
    class MacroCommand{
        constructor(){
            this.commands = [];
        }
        // Add child object logic
        add(command){
            console.log(this);
            this.commands.push(command);
        }
        // Execute the parent object logic
        execute(){
            for(let i = 0; i < this.commands.length; i++){
                this.commands[i].execute(); }}}const macroCommand = new MacroCommand();
    const name1Command = {
        execute:() = >{
            console.log('jackson'); }}const name2Command = {
        execute:() = >{
            console.log('bear');
        }
    }
    macroCommand.add(name1Command);
    macroCommand.add(name2Command);
    macroCommand.execute();
Copy the code

Decorator mode

Add responsibilities to objects dynamically while the program is running without changing the object itself.

Adapter mode

Mainly to solve the interface incompatibility between two software, do not need to change the existing interface, can make them work together.

Before usingWe’re not using an adapter here, so there’s not a lot of stuff here, and it looks pretty clear to us, but if there are a lot of things you need to always if else. modified

    // Adapter mode
    const aMap = {
        show:() = > {
            console.log('A Map Rendering')}}const bMap = {
        display:() = > {
            console.log('B Map Rendering')}}// Add the adapter
    const bMapAdapter = {
        show:() = > {
            returnbMap.display(); }}const renderMap = (map) = > {
        if (map.show instanceof Function){
            map.show();
        }
    }
    renderMap(aMap);
    renderMap(bMapAdapter); // Instead of passing the bMap parameter, the adapter is passed
Copy the code

We add a layer of adapters in the middle, so we don’t have to do so much if else judgment, logic is clear, and we don’t need to change the underlying interface logic.

conclusion

In the use of design patterns can not abuse design patterns, there are more than 20 kinds of design patterns, are summed up by the predecessors for decades, in daily development, we should also pay attention to the principle of design patterns, more thinking, so as to write elegant and efficient code. About JS Design Patterns (1) – Digging gold (juejin. Cn)