js的常用设计模式

78 阅读1分钟

设计模式:设计模式是一套众人知晓的,代码设计经验的总结

1.发布订阅者模式和观察者模式

1-1观察者模式

    // 观察者模式 和 发布订阅者模式
    class Subject {
        constructor() {
            this.callback = [];  // 观察者的列表
        }
        add(fun) {
            this.callback.push(fun);
        }
        notify() {
            for( let observe of this.callback) {
                observe.update();
            }

        }
    }

    class Observed {
        constructor(name) {
            this.name = name;
        }
        update() {
            console.log(this.name , '我更新了');
        }
    }

    const oberve1 = new Observed('观察者1');
    const oberve2 = new Observed('观察者2');

    const subject = new Subject();

    subject.add(oberve1);
    subject.notify();

    subject.add(oberve2);
    subject.notify();

1-2 发布订阅者模式

//  发布订阅者模式 
    class Event{
        constructor(){
            this.callbacks = {}
        }
        $off(name){
            this.callbacks[name] = null
        }
        $emit(name, args){
            let cbs = this.callbacks[name]
            if (cbs) {
                cbs.forEach(c=>{
                    c.call(this, args)
                })
              }
        }
        $on(name, fn){
            (this.callbacks[name] || (this.callbacks[name] = [])).push(fn)
        }
    }
    let event = new Event()
    event.$on('event1', function(arg){
        console.log('事件1',arg)
    })
    event.$on('event1', function(arg){
        console.log('又一个时间1',arg)
    })
    event.$on('event2', function(arg){
        console.log('事件2',arg)
    })
    
    event.$emit('event1',{name:'开课吧'})
    // event.$emit('event2',{name:'全栈'})
    
   event.$off('event1')
   event.$emit('event1',{name:'开课吧'})