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>
相关推荐
遇到困难睡大觉哈哈1 小时前
Harmony os 静态卡片(ArkTS + FormLink)详细介绍
前端·microsoft·harmonyos·鸿蒙
用户47949283569152 小时前
Bun 卖身 Anthropic!尤雨溪神吐槽:OpenAI 你需要工具链吗?
前端·openai·bun
p***43482 小时前
前端在移动端中的网络请求优化
前端
g***B7382 小时前
前端在移动端中的Ionic
前端
拿破轮2 小时前
使用通义灵码解决复杂正则表达式替换字符串的问题.
java·服务器·前端
whltaoin2 小时前
【 Web认证 】Cookie、Session 与 JWT Token:Web 认证机制的原理、实现与对比
前端·web·jwt·cookie·session·认证机制
Aerelin3 小时前
爬虫playwright入门讲解
前端·javascript·html·playwright
笙年3 小时前
JavaScript Promise,包括构造函数、对象方法和类方法
开发语言·javascript·ecmascript
桜吹雪3 小时前
LangChain.js/DeepAgents可观测性
javascript·人工智能
5***o5003 小时前
前端在移动端中的NativeBase
前端