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>
相关推荐
一个水瓶座程序猿.几秒前
Vue3 中使用 Vueuse
前端·javascript·vue.js
夏梦春蝉几秒前
ES6从入门到精通:Symbol与迭代器
前端·javascript·es6
今夜星辉灿烂3 分钟前
nestjs微服务-系列2
javascript·后端
一个水瓶座程序猿.4 分钟前
ES6数组的`flat()`和`flatMap()`函数用法
前端·ecmascript·es6
DKPT10 分钟前
Java设计模式之结构型模式(外观模式)介绍与说明
java·开发语言·笔记·学习·设计模式
缘来是庄12 分钟前
设计模式之外观模式
java·设计模式·外观模式
你是橙子那我是谁15 分钟前
设计模式之外观模式:简化复杂系统的优雅之道
设计模式
袁煦丞20 分钟前
AI直接出答案!Perplexica开源搜索引擎:cpolar内网穿透实验室第534个成功挑战
前端·程序员·远程工作
Hilaku22 分钟前
用“人话”讲明白10个最常用的正则表达式
前端·javascript·正则表达式
木叶丸31 分钟前
跨平台方案该如何选择?
android·前端·ios