裝飾者模式
- 符合開放關(guān)閉原則
- 裝飾者模式和代理模式非常像,代理模式更加強(qiáng)調(diào)的是一種靜態(tài)的關(guān)系,即一開始就確定了代理與本體的關(guān)系,
- 而裝飾者模式更加強(qiáng)調(diào)的是,一種動態(tài)的關(guān)系, 如比如某個模塊的功能寫好了,想要動態(tài)的給這個模塊添加一些功能,比如再這個模塊函數(shù)后面添加一個log日志等
- 代理模式通常只是一層代理-本體,而裝飾者模式經(jīng)常形成一條長長的裝飾鏈
- 裝飾者模式也是包裝器模式(wrapper)
比如寫個AOP
//before也相當(dāng)于wrapper 給目標(biāo)函數(shù)加上一個before裝飾
Function.prototype.before = function(before) {
var _this = this;
return function(args) {
before.apply(this, args);
_this.apply(this, args);
}
}
//給目標(biāo)函數(shù)加上after裝飾
Function.prototype.after = function(after) {
var _this = this;
return function(args) {
_this.apply(this, args);
after.apply(this, args);
}
}
function sendEmail() {
console.log('sendEmail');
}
var wrapper = sendEmail.before(function() {console.log('check email')})
.after(function () {console.log('check response')})
.after(function() {console.log('logger')});
wrapper();
// check email
// sendEmail
// check response
// logger