天天一個設計模式之裝飾者模式

做者按:《天天一個設計模式》旨在初步領會設計模式的精髓,目前採用 javascriptpython兩種語言實現。誠然,每種設計模式都有多種實現方式,但此小冊只記錄最直截了當的實現方式 :)

原文地址是:《天天一個設計模式之裝飾者模式》javascript

歡迎關注我的技術博客:godbmw.com。每週 1 篇原創技術分享!開源教程(webpack、設計模式)、面試刷題(偏前端)、知識整理(每週零碎),歡迎長期關注!前端

若是您也想進行知識整理 + 搭建功能完善/設計簡約/快速啓動的我的博客,請直接戳theme-bmwjava

0. 項目地址

1. 什麼是「裝飾者模式」?

裝飾者模式:在 不改變對象自身的基礎上, 動態地添加功能代碼。

根據描述,裝飾者顯然比繼承等方式更靈活,並且不污染原來的代碼,代碼邏輯鬆耦合。python

2. 應用場景

裝飾者模式因爲鬆耦合,多用於一開始不肯定對象的功能、或者對象功能常常變更的時候。
尤爲是在參數檢查參數攔截等場景。webpack

3. 代碼實現

3.1 ES6 實現

ES6的裝飾器語法規範只是在「提案階段」,並且不能裝飾普通函數或者箭頭函數。git

下面的代碼,addDecorator能夠爲指定函數增長裝飾器。es6

其中,裝飾器的觸發能夠在函數運行以前,也能夠在函數運行以後。github

注意:裝飾器須要保存函數的運行結果,而且返回。web

const addDecorator = (fn, before, after) => {
  let isFn = fn => typeof fn === "function";

  if (!isFn(fn)) {
    return () => {};
  }

  return (...args) => {
    let result;
    // 按照順序執行「裝飾函數」
    isFn(before) && before(...args);
    // 保存返回函數結果
    isFn(fn) && (result = fn(...args));
    isFn(after) && after(...args);
    // 最後返回結果
    return result;
  };
};

/******************如下是測試代碼******************/

const beforeHello = (...args) => {
  console.log(`Before Hello, args are ${args}`);
};

const hello = (name = "user") => {
  console.log(`Hello, ${name}`);
  return name;
};

const afterHello = (...args) => {
  console.log(`After Hello, args are ${args}`);
};

const wrappedHello = addDecorator(hello, beforeHello, afterHello);

let result = wrappedHello("godbmw.com");
console.log(result);

3.2 Python3 實現

python直接提供裝飾器的語法支持。用法以下:面試

# 不帶參數
def log_without_args(func):
    def inner(*args, **kw):
        print("args are %s, %s" % (args, kw))
        return func(*args, **kw)
    return inner

# 帶參數
def log_with_args(text):
    def decorator(func):
        def wrapper(*args, **kw):
            print("decorator's arg is %s" % text)
            print("args are %s, %s" % (args, kw))
            return func(*args, **kw)
        return wrapper
    return decorator

@log_without_args
def now1():
    print('call function now without args')

@log_with_args('execute')
def now2():
    print('call function now2 with args')

if __name__ == '__main__':
    now1()
    now2()

其實python中的裝飾器的實現,也是經過「閉包」實現的。

以上述代碼中的now1函數爲例,裝飾器與下列語法等價:

# ....
def now1():
    print('call function now without args')
# ... 
now_without_args = log_without_args(now1) # 返回被裝飾後的 now1 函數
now_without_args() # 輸出與前面代碼相同

4. 參考

相關文章
相關標籤/搜索