做者按:《天天一個設計模式》旨在初步領會設計模式的精髓,目前採用
javascript
和python
兩種語言實現。誠然,每種設計模式都有多種實現方式,但此小冊只記錄最直截了當的實現方式 :)javascript
原文地址是:《天天一個設計模式之裝飾者模式》。java
若是您也想進行知識整理 + 搭建功能完善/設計簡約/快速啓動的我的博客,能夠直接戳:theme-bmwpython
裝飾者模式:在不改變對象自身的基礎上,動態地添加功能代碼。git
根據描述,裝飾者顯然比繼承等方式更靈活,並且不污染原來的代碼,代碼邏輯鬆耦合。es6
裝飾者模式因爲鬆耦合,多用於一開始不肯定對象的功能、或者對象功能常常變更的時候。 尤爲是在參數檢查、參數攔截等場景。github
ES6的裝飾器語法規範只是在「提案階段」,並且不能裝飾普通函數或者箭頭函數。設計模式
下面的代碼,addDecorator
能夠爲指定函數增長裝飾器。閉包
其中,裝飾器的觸發能夠在函數運行以前,也能夠在函數運行以後。app
注意:裝飾器須要保存函數的運行結果,而且返回。函數
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);
複製代碼
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() # 輸出與前面代碼相同
複製代碼