每天一个设计模式之装饰者模式

作者 : 开心源码 本文共1973个字,预计阅读时间需要5分钟 发布时间: 2022-05-12 共190人阅读

作者按:《每天一个设计模式》旨在初步领会设计模式的精髓,目前采用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_argsdef 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. 参考

  • JavaScript Decorators: What They Are and When to Use Them
  • 《阮一峰ES6-Decorator》
  • 《廖雪峰python-Decorator》

说明
1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是摆设,本站源码仅提供给会员学习使用!
7. 如遇到加密压缩包,请使用360解压,如遇到无法解压的请联系管理员
开心源码网 » 每天一个设计模式之装饰者模式

发表回复