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

装饰器模式

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

类似于 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());
相关推荐
木斯佳5 小时前
HarmonyOS 6 三方SDK对接:从半接模式看Share Kit原理——系统分享的运行机制与设计理念
设计模式·harmonyos·架构设计·分享·半接模式
yydonk5 小时前
像 Agent 一样思考:从 Claude Code 架构演进看 AI Agent 工具设计
设计模式
Jackson_Li8 小时前
大多数人对 Claude Code Skills 的理解,在第一步就错了
人工智能·设计模式
似水明俊德12 小时前
13-C#.Net-设计模式六大原则-学习笔记
笔记·学习·设计模式·c#·.net
wangchunting14 小时前
Java设计模式
java·单例模式·设计模式
孟陬1 天前
国外技术周刊 #3:“最差程序员”带动高效团队、不写代码的创业导师如何毁掉创新…
前端·后端·设计模式
砍光二叉树1 天前
【设计模式】结构型-代理模式
设计模式·系统安全·代理模式
新缸中之脑1 天前
AI智能体五大设计模式
人工智能·机器学习·设计模式
砍光二叉树1 天前
【设计模式】结构型-装饰器模式
设计模式·装饰器模式
han_1 天前
JavaScript设计模式(三):代理模式实现与应用
前端·javascript·设计模式