【设计模式】装饰器模式和适配模式

装饰器模式

装饰器模式能够很好的对已有功能进行拓展,这样不会更改原有的代码,对其他的业务产生影响,这方便我们在较少的改动下对软件功能进行拓展。

类似于 router 的前置守卫和后置守卫。

js 复制代码
Function.prototype.before = function (beforeFn) {
    const _this = this;
    return function () {
        // 先执行前置函数的调用
        beforeFn.apply(this, arguments);
        // 再执行当前函数的调用
        const result = _this.apply(this, arguments);
        return result;
    }
}
Function.prototype.after = function (afterFn) {
    const _this = this;
    return function () {
        // 先执行当前函数的调用
        const result = _this.apply(this, arguments);
        // 再执行后置函数的调用
        afterFn.apply(this, arguments);
        return result;
    }
}
function fn() {
    console.log('fn')
    return 'fn';
}

let fnn = fn.before(function () {
    console.log('前置函数调用')
}).after(function () {
    console.log('后置函数调用')
})
fnn()

适配模式

将一个类的接口转换成客户希望的另一个接口。适配器模式让那些接口不兼容的类可以一起工作。

比如 axios 在 nodejs 和浏览器环境下都可以使用,本质上就是使用了适配器模式。

js 复制代码
class TencentMap {
    show() {
        console.log('渲染腾讯地图');
    }
}
class BaiduMap {
    display() {
        console.log('渲染百度地图');
    }
}
// 写一个适配器 让腾讯地图适配百度地图的方法
class TencentAdapter extends TencentMap{
    constructor() {
        super();
    }
    display() {
        this.show();
    }
}
function renderMap(map) {
    map.display();
}
renderMap(new TencentAdapter());
renderMap(new BaiduMap());
相关推荐
绿豆人14 小时前
Go设计模式学习
学习·设计模式·golang
逮到647了16 小时前
23种设计模式简述
设计模式
爱吃烤鸡翅的酸菜鱼17 小时前
【Java】封装位运算通用工具类——用一个整数字段替代几十个布尔列,极致节省存储空间
java·开发语言·设计模式·工具类·位运算·合成复用原则
geovindu18 小时前
go: Model,Interface,DAL ,Factory,BLL using mysql
开发语言·mysql·设计模式·golang·软件构建
guojb82418 小时前
当 Vue 3 遇上桥接模式:手把手教你优雅剥离虚拟滚动的业务大泥球
vue.js·设计模式
我登哥MVP19 小时前
【Spring6笔记】 - 15 - Spring中的八大设计模式
java·spring boot·笔记·spring·设计模式·intellij-idea
无籽西瓜a20 小时前
【西瓜带你学设计模式 | 第十六期 - 迭代器模式】迭代器模式 —— 统一遍历实现、优缺点与适用场景
java·后端·设计模式·迭代器模式·软件工程
程序员小寒20 小时前
JavaScript设计模式(十):模板方法模式实现与应用
前端·javascript·设计模式·模板方法模式
likerhood20 小时前
关于三种工厂的设计模式总结
设计模式
榴莲omega21 小时前
第14天:React 工程化与设计模式
前端·react.js·设计模式