【设计模式】职责链模式

使多个对象都有机会处理请求,从而避免了请求的发送者与多个接收者直接的耦合关系,将这些接收者连接成一条链,顺着这条链传递该请求,直到找到能处理该请求的对象。

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<input type="text" id="input">
<button id="button">注册</button>
<script>
    function checkEmpty() {
        if (input.value.length === 0) {
            alert('不能为空');
            return false;
        } else {
            return true;
        }
    }
    function checkLength() {
        if (input.value.length < 6) {
            alert('长度不能小于6');
            return false;
        } else {
            return true;
        }
    }
    class Chain{
        constructor(fn) {
            this.fn = fn;
            this.next = null;
        }
        setNext(next) {
            this.next = next;
        }
        run() {
            let result = this.fn.apply(this, arguments);
            if (result === true && this.next !== null) {
                return this.next.run.apply(this.next, arguments);
            }
            return result;
        }
    }
    let chain1 = new Chain(checkEmpty);
    let chain2 = new Chain(checkLength);
    chain1.setNext(chain2);
    button.onclick = function () {
        chain1.run();
    }
</script>
</body>
</html>
相关推荐
茶本无香20 小时前
设计模式之八: 适配器模式解释及应用
java·设计模式·适配器模式
喝可乐的希饭a20 小时前
AI Agent 的九种设计模式
人工智能·设计模式
txinyu的博客21 小时前
常见设计模式
设计模式
云游云记1 天前
php设计模式总结
开发语言·设计模式·php
Engineer邓祥浩1 天前
设计模式学习(20) 23-18 中介者模式
学习·设计模式·中介者模式
不穿格子的程序员1 天前
设计模式篇2——观察者模式:以直播间送礼系统举例
java·观察者模式·设计模式
小码过河.1 天前
设计模式——解释器模式
java·设计模式·解释器模式
老蒋每日coding1 天前
AI Agent 设计模式系列(二十)—— 优先级排序设计模式
人工智能·设计模式
鱼跃鹰飞1 天前
设计模式系列:工厂模式
java·设计模式·系统架构
老蒋每日coding2 天前
AI Agent 设计模式系列(十九)—— 评估和监控模式
人工智能·设计模式