es9 设计模式

1. 工厂模式

class CarMaker {
    constructor () {
        this.doors = 0;
    }
    drive () {
        console.log(`我有${this.doors}`);
    }


    static factory (type) {
        return new CarMaker[type]();
    }
}


CarMaker.Compact = class compact extends CarMaker {
    constructor () {
        super()
        this.doors = 0;
    }
}
CarMaker.factory('Compact').drive();

2. 单例模式 


'use strict';
let __instance = (() => {
    let instance;
    return (newInstance) => {
        if (newInstance) instance = newInstance;
        return instance;
    }
})();
class Universe {
    constructor () {
        if (__instance()) return __instance();
        this.foo = 'bar';
        __instance(this);

    }
}


let ul = new Universe();
let ul2 = new Universe();
console.log(ul === ul2)


3. 迭代器模式

const myIt = {};
myIt[Symbol.iterator] = function* () {
    yield 1;
    yield 2;
    yield 3;
}
const result = [...myIt];
console.log(result)



4. 代理模式

class Real {
    doSth () {
        console.log('doSth');
    }
}


class NewProxy extends Real {
    constructor () {
        super();
    }


    doSth () {
        setTimeout(() => {
            new Real().doSth();
        }, 1000 * 3 )
    }
}


new NewProxy().doSth();

 

你可能感兴趣的:(前端开发)