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

装饰器模式

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

类似于 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());
相关推荐
资深web全栈开发5 小时前
设计模式之解释器模式 (Interpreter Pattern)
设计模式·解释器模式
漠月瑾-西安6 小时前
React-Redux Connect 高阶组件:从“桥梁”到“智能管家”的深度解析
react.js·设计模式·react-redux·高阶组件·connect高阶租单间·原理理解
J_liaty13 小时前
23种设计模式一备忘录模式
设计模式·备忘录模式
驴儿响叮当201016 小时前
设计模式之建造者模式
设计模式·建造者模式
知识即是力量ol16 小时前
口语八股—— Spring 面试实战指南(终篇):常用注解篇、Spring中的设计模式
java·spring·设计模式·面试·八股·常用注解
茶本无香18 小时前
【无标题】
java·设计模式·策略模式
郝学胜-神的一滴1 天前
当AI遇见架构:Vibe Coding时代的设计模式复兴
开发语言·数据结构·人工智能·算法·设计模式·架构
『往事』&白驹过隙;1 天前
浅谈PC开发中的设计模式搬迁到ARM开发
linux·c语言·arm开发·设计模式·iot
闻哥1 天前
23种设计模式深度解析:从原理到实战落地
java·jvm·spring boot·设计模式·面试