js设计模式之命令模式

xml 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>命令模式</title>
</head>
<body>
<button id="btn1">刷新菜单</button>
<button id="btn2">增加菜单</button>
<button id="btn3">删除菜单</button>
<script>
    /**
     * 命令模式(Command)的定义是:用于将一个请求封装成一个对象,从而使你可用不同的请求对客户进行参数化;
     * 对请求排队或者记录请求日志,以及执行可撤销的操作。也就是说改模式旨在将函数的调用、请求和操作封装成一个单一的对象,然后对这个对象进行一系列的处理。
     * 此外,可以通过调用实现具体函数的对象来解耦命令对象与接收对象。
     */
        //定义一个命令发布者(执行类)
    class Executor {
        setCommand(btn, command) {
            btn.onclick = function () {
                command.execute();
            }
        }
    }

    //定义一个命令接受者
    class Menu {
        refresh() {
            console.log('刷新菜单');
        }

        addMenu() {
            console.log('添加菜单');
        }
        deleteMenu() {
            console.log('删除菜单');
        }
    }

    //刷新菜单命令对象
    class RefreshMenu {
        constructor(receiver) {
            this.receiver = receiver;
        }
        //爆漏出统一的接口
        execute(){
            this.receiver.refresh();
        }
    }
    //增加菜单
    class AddMenu {
        constructor(receiver) {
            this.receiver = receiver;
        }
        //爆漏出统一的接口
        execute(){
            this.receiver.addMenu();
        }
    }
    //删除菜单
    class DeleteMenu {
        constructor(receiver) {
            this.receiver = receiver;
        }
        execute(){
            this.receiver.deleteMenu();
        }
    }
    const menu = new Menu();
    const executor = new Executor();
    //刷新菜单
    const refreshMenu = new RefreshMenu(menu);
    //给按钮添加刷新操作
    let ben1=document.getElementById('btn1');
    executor.setCommand(ben1, refreshMenu);
    //给按钮2添加增加菜单操作
    let addMenu=new AddMenu(menu);
    let ben2=document.getElementById('btn2');
    executor.setCommand(ben2, addMenu);
    //删除菜单
    let deleteMenu=new DeleteMenu(menu);
    let ben3=document.getElementById('btn3');
    executor.setCommand(ben3, deleteMenu);
</script>
</body>
</html>
相关推荐
王同学要变强2 分钟前
【深入学习Vue丨第二篇】构建动态Web应用的基础
前端·vue.js·学习
社恐的下水道蟑螂13 分钟前
从字符串到像素:深度解析 HTML/CSS/JS 的页面渲染全过程
javascript·css·html
程序定小飞14 分钟前
基于springboot的web的音乐网站开发与设计
java·前端·数据库·vue.js·spring boot·后端·spring
Hello_WOAIAI17 分钟前
2.4 python装饰器在 Web 框架和测试中的实战应用
开发语言·前端·python
FinClip24 分钟前
凡泰极客亮相香港金融科技周,AI助力全球企业构建超级应用
前端
阿四43 分钟前
【Nextjs】为什么server action中在try/catch内写redirect操作会跳转失败?
前端·next.js
申阳1 小时前
Day 6:04. 基于Nuxt开发博客项目-LOGO生成以及ICON图标引入
前端·后端·程序员
中国lanwp1 小时前
npm中@your-company:registry 和 registry 的区别
前端·npm·node.js
Bacon1 小时前
Electron 应用商店:开箱即用工具集成方案
前端·github
行走的陀螺仪1 小时前
uni-app + Vue3 实现折叠文本(超出省略 + 展开收起)
前端·javascript·css·uni-app·vue3