单例模式、发布订阅、观察者模式、迭代器模式

2019-05-13  本文已影响0人  liuxinya

单例模式

var aa = (function () {
    var instance
    return function () {
        function Modal() {
            this.init();
        }
        Modal.prototype.init = function () {
            console.log('创建了modal')
        }
        if (!instance) { 
            console.log(111)  // 只打印一次 
            instance = new Modal();
        }
        return instance;
    }
})()
let a = aa()
let b = aa()
console.log(a, b , a == b)

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

发布订阅模式 - 贼简单实现

class Observable {
    private handlers: {
        [props: string]: fn[]
    } = {};
    subscribe(key: string, fun: fn) {
        if (!this.handlers[key]) this.handlers[key] = [];
        this.handlers[key].push(fun);
    }
    unSubscribe(key: string) { 
        delete this.handlers[key];
    }
    publish<K>(key: string, val: K) {
        let handlers = this.handlers[key] || [];
        handlers.forEach(item => {
            item(val)
        })
    }
 }
type fn = (v: any) => void;

// test
var observer = new Observable();
observer.subscribe('name', (val) => {
    console.log(`1 name is ${val}`)
})
observer.subscribe('name', (val) => {
    console.log(`2 name is ${val}`)
})
observer.subscribe('age', (val) => {
    console.log(`1 age is ${val}`)
})
observer.publish<string>('name', 'liuxinya')
observer.publish<number>('age', '18')

观察者模式

Iterator Pattern

class IteratorFromArray {
    _array: any[]
    _cursor: number
    constructor(arr: any[]) {
        this._array = arr;
        this._cursor = 0;
    }
  
    next() {
        return this._cursor < this._array.length ?
        { value: this._array[this._cursor++], done: false } :
        { done: true };
    }
    map(callback: (v: any) => {done: boolean, value: any}) {
        let iterator = new IteratorFromArray(this._array)
        return {
            next: () => {
                const { done, value } = iterator.next()
                return {
                    done,
                    value: value ? callback(value) : undefined
                }
            }
        }  
    }
}
let test = new IteratorFromArray([1, 2, 3, 4])
console.log(test.next()) // {value: 1, done: false}
console.log(test.next())  //  {value: 2, done: false}
console.log(test.next()) //  {value: 3, done: false}

let testMap = test.map(value => value + 1)
console.log(testMap.next()) //{done: false, value: 2}
console.log(testMap.next()) // {done: false, value: 3}
console.log(testMap.next())
console.log(testMap.next())
console.log(testMap.next()) // {done: true, value: undefined}
上一篇下一篇

猜你喜欢

热点阅读