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

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

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

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

如果您也想進行知識整理 + 搭建功能完善/設計簡約/快速啓動的個人博客,請直接戳theme-bmw

0. 項目地址

1. 什麼是“裝飾者模式”?

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

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

2. 應用場景

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

3. 代碼實現

3.1 ES6 實現

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

下面的代碼,addDecorator可以爲指定函數增加裝飾器。

其中,裝飾器的觸發可以在函數運行之前,也可以在函數運行之後。

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

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. 參考

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章