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>
相关推荐
fruge7 分钟前
仿写优秀组件:还原 Element Plus 的 Dialog 弹窗核心逻辑
前端
an869500116 分钟前
vue新建项目
前端·javascript·vue.js
w***95491 小时前
SQL美化器:sql-beautify安装与配置完全指南
android·前端·后端
顾安r2 小时前
11.22 脚本打包APP 排错指南
linux·服务器·开发语言·前端·flask
万邦科技Lafite2 小时前
1688图片搜索商品API接口(item_search_img)使用指南
java·前端·数据库·开放api·电商开放平台
czhc11400756632 小时前
c# 1121 构造方法
java·javascript·c#
yinuo3 小时前
网页也懂黑夜与白天:系统主题自动切换
前端
Coding_Doggy3 小时前
链盾shieldchain | 项目管理、DID操作、DID密钥更新消息定时提醒
java·服务器·前端
用户21411832636023 小时前
dify案例分享-国内首发!手把手教你用Dify调用Nano Banana2AI画图
前端
wa的一声哭了3 小时前
Webase部署Webase-Web在合约IDE页面一直转圈
linux·运维·服务器·前端·python·区块链·ssh