我想学会设计模式之装饰者模式
这是我参与8月更文挑战的第11天,活动详情查看:8月更文挑战
我想学会设计模式之装饰者模式
装饰者模式:在不改变对象自身的基础上,动态地添加功能代码。
什么是“装饰者模式”?
装饰者模式:在不改变对象自身的基础上,动态地添加功能代码。
根据描述,装饰者显然比继承等方式更灵活,而且不污染原来的代码,代码逻辑松耦合。装饰者模式就像打包一个快递 ;比如我卖了一个陶瓷,一本书,其核心就是我们卖的东西。这些东西我们不可能直接去卖出去,因此我们会在外面包装好多保护东西,如泡沫塑料等等。
优缺
- 优点: 装饰类和被装饰类可以独立发展,不会相互耦合,装饰模式是继承的一个替代模式,装饰模式可以动态扩展一个实现类的功能。
- 缺点: 多层装饰比较复杂。
应用场景
装饰者模式由于松耦合,多用于一开始不确定对象的功能、或者对象功能经常变动的时候。
尤其是在参数检查、参数拦截等场景。
代码实现
ES6 实现
ES6 的装饰器语法规范只是在“提案阶段”,而且不能装饰普通函数或者箭头函数。
下面的代码,addDecorator可以为指定函数增加装饰器。
其中,装饰器的触发可以在函数运行之前,也可以在函数运行之后。
注意:装饰器需要保存函数的运行结果,并且返回。
const isFn = fn => typeof fn === "function";
const addDecorator = (fn, before, after) => {
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);