Functional equivalent of decorator pattern?

后端 未结 10 2112
悲&欢浪女
悲&欢浪女 2021-02-02 06:34

What is the functional programming equivalent of the decorator design pattern?

For example, how would you write this particular example in a functional style?

10条回答
  •  一整个雨季
    2021-02-02 07:23

    Here's an example using JSGI, a web server API for JavaScript:

    function Log(app) {
        return function(request) {
             var response = app(request);
             console.log(request.headers.host, request.path, response.status);
             return response;
         };
     }
    
     var app = Logger(function(request) {
         return {
             status: 200,
             headers: { "Content-Type": "text/plain" },
             body: ["hello world"]
         };
      }
    

    Compliant middleware can be stacked, of course (e.x. Lint(Logger(ContentLength(app))))

提交回复
热议问题