Skip to content

Latest commit

 

History

History
47 lines (43 loc) · 1.59 KB

职责链模式.md

File metadata and controls

47 lines (43 loc) · 1.59 KB

职责链模式

职责链上的处理者负责处理请求,客户只需要将请求发送到职责链上即可,无须关心请求的处理细节和请求的传递,所以职责链将请求的发送者和请求的处理者解耦了。

现实中,后门上车向投币箱传递硬币就是职责链模式。你可以传给A、传给B、传给C,不一定是ABC的顺序,但目标是投币箱。

class Middleware {
    constructor() {
        this.middlewares = [];
    }
    use(fn) {
        if(typeof fn !== 'function') {
            throw new Error('Middleware must be function, but get ' + typeof fn);
        } 
        this.middlewares.push(fn);
        return this;
    }
    compose() {
        const middlewares = this.middlewares;
        return dispatch(0);
        function dispatch(index) {
            const middleware = middlewares[index];
            if (!middleware) {return;}
            try{
                const ctx = {};
                const result = middleware(ctx, dispatch.bind(null, index + 1));
                return Promise.resolve(result);
            } catch(err) {
                return Promise.reject(err);
            }
        }
    }
}

// 使用
const middleware = new Middleware();
middleware.use(async (ctx, next) => {
    console.log(1);
    await next();
    console.log(2);
});
middleware.use(async (ctx, next) => {
    console.log(3);
    await next();
    console.log(4);
});
middleware.compose();// 1 3 4 2