头图

Preface

A pattern is a solution to a problem in a certain context.

Design pattern (Design pattern) is a set of code design experience that has been used repeatedly, most people know, classified and cataloged.

In order to ensure the reliability of the code, improve the reuse rate of the code, and make the code easier to maintain and read, we need to understand and use design patterns reasonably.

In daily development, your processing methods in some specific scenarios may not be very ideal. At this time, some design patterns can allow you to implement these logics elegantly and efficiently. Here are some of them although not the most complete, but they must be the most. Commonly used design patterns.

Singleton mode:

definition of A class only returns one instance, once it is created and called again, it returns directly.

usage scenarios: such as custom pop-up windows, no matter how many calls in your program, you should only create a pop-up window object.

class CreateUser {
    constructor(name) {
        this.name = name;
        this.getName();
    }
    getName() {
        return this.name;
    }
};

const ProxyMode = (() => {
    let instance = null;
    return (name) => {
        if(!instance) {
            instance = new CreateUser(name);
        }
        return instance;
    }
})();

let a = ProxyMode('vn');
let b = ProxyMode('lb');

console.log(a, b);   // vn  vn    单例模式只会创建一次实例

Strategy mode:

definition: defines a strategy class only to focus on the implementation of each method algorithm, and defines an interface to call these methods.

Features : The code is elegant and highly readable.

// 策略类
const levelObj = {
    "A": money => money * 4,
    "B": money => money * 3,
    "C": money => money * 2
}

// 环境类  封装调用接口
const getMoney = (level, money) => levelObj[level](money);

console.log(getMoney('A', 200))   // 800

Agency mode:

definition: provides a substitute or placeholder for an object in order to control access to it.

usage scenario: such as lazy loading of images, first cache dynamic loading, and pass in src if necessary.

const imgFunc = (() => {
    let imgNode = document.createElement('img');
    document.body.appendChild(imgNode);
    return {
        setSrc: (src) => {
            imgNode.src = src;
        }
    }
})();

const ProxyImg = (() => {
    let img = new Image();
    img.onload = () => {
        let node = document.getElementsByTagName('img')
        imgFunc.setSrc(img.src);
    }
    return {
        setSrc: (src) => {
            imgFunc.setSrc('../C3photo/jacky/1.jpg');
            img.src = src;
        }
    }
})();

ProxyImg.setSrc('../C3photo/jacky/2.jpg');

Decorator mode:

definition: decorator mode can dynamically add responsibilities to the object during the running of the program without changing the object itself.

usage scenario: similar to an interceptor, adding pre- and post-events of the object, etc.

Function.prototype.before = function(beforefn) {
    let _self = this;                          
    return function () {
        beforefn.apply(this, arguments);
        return _self.apply(this, arguments);
    }
}
Function.prototype.after = function(afterfn) {
    let _self = this;
    return function(){
        let ret = _self.apply(this, arguments);
        afterfn.apply(this, arguments);
        return ret;
    }
}
let func = function() {
    console.log('2');
}
//func1和func3为挂载函数
let func1 = function() {
    console.log('1');
}
let func3 = function() {
    console.log('3');
}

func = func.before(func1).after(func3);
func();   // 1  2  3

Publish and subscribe mode:

definition: subscribers (Subscriber) register the event they want to subscribe to (Subscribe) to the dispatch center (Event Channel), when the publisher (Publisher) publishes the event (Publish Event) to the dispatch center, that is, when the event is triggered , The processing code registered to the dispatch center by the dispatch center unified dispatch (Fire Event) subscribers.

Usage scenario: WeChat public account subscription

let eventEmitter = {
    list: {}, 

    on(event, fn) {
        // 订阅
        let _this = this;
        _this.list[event] = _this.list[event] || [];
        _this.list[event].push(fn);
        return _this;
    },

    emit() {
        // 发布
        let _this = this;
        let event = [].shift.call(arguments),
            fns = _this.list[event];
        if (fns && fns.length) {
            fns.forEach((fn) => fn.apply(_this, arguments));
        }
        return _this;
    },

    off(event, fn) {
        // 取消订阅
        let _this = this;
        let fns = _this.list[event];
        if (!fns) return false;
        if (!fn) {
            fns.length = 0;
        } else {
            for (let i = 0; i < fns.length; i++) {
                if (fns[i] === fn || fns[i].fn === fn) {
                    fns.splice(i, 1);
                    break;
                }
            }
        }
    }
};

const user1 = (content) => {
    console.log("用户1订阅了:", content);
};

const user2 = (content) => {
    console.log("用户2订阅了:", content);
};

const user3 = (content) => {
    console.log("用户3订阅了:", content);
};

// 订阅
eventEmitter.on("article1", user1);
eventEmitter.on("article1", user2);
eventEmitter.on("article2", user3);

eventEmitter.emit("article1", "Javascript 发布-订阅模式");
eventEmitter.emit("article2", "Javascript 观察者模式");

eventEmitter.off("article1", user1);
eventEmitter.emit("article1", "Javascript 发布-订阅模式");

//用户1订阅了: Javascript 发布-订阅模式
//用户2订阅了: Javascript 发布-订阅模式
//用户3订阅了: Javascript 观察者模式
//用户2订阅了: Javascript 发布-订阅模式

Summarize

Learning design patterns not only enables us to make good use of these successful design patterns, but more importantly, it enables us to deeply understand object-oriented design ideas.

~

~ End of this article, thanks for reading!

~

Learn interesting knowledge, meet interesting friends, and create interesting souls!

Hello everyone, I is [ programming Samadhi of〗 of hermit king , my public number is " programming Samadhi " welcome attention, we hope the exhibitions!

Come, with expectations, I have Moxiang to greet you! You return, no matter the gains or losses, only with the lingering rhyme as a gift!

Pay equal attention to knowledge and skills, both internal and external skills, both theory and practice must be grasped, and both hands must be hard!


编程三昧
54 声望10 粉丝

学习有趣的知识,交识有趣的朋友,造就有趣的灵魂!