【设计模式】职责链模式

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

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>
相关推荐
路弥行至9 小时前
【Head First 设计模式】第 2 章:观察者模式 —— 用现代 C++ 重新解读“交互对象的松耦合
c++·经验分享·笔记·观察者模式·设计模式·入门教程·headfirst
YYYing.9 小时前
【设计模式系列 (九) 】装饰器模式
c++·后端·设计模式·装饰器模式·c/c++
沫璃染墨13 小时前
《从零入门Linux系统篇(五十六):线程篇·九——生产者消费者模型:从条件变量到BlockingQueue实现》
linux·服务器·c++·驱动开发·设计模式·架构·系统架构
c萱2 天前
AI产品经理——01基础认知篇
设计模式·prompt·aigc·产品经理·ai编程·gitcode·ai-native
YYYing.2 天前
【设计模式系列 (八) 】组合模式
c++·后端·设计模式·组合模式·c/c++
geovindu2 天前
rust: Composite Pattern
开发语言·后端·设计模式·rust·组合模式
YYYing.2 天前
【设计模式系列 (七) 】桥接模式
c++·后端·设计模式·桥接模式
阿狗童鞋3 天前
设计模式实战指南
设计模式
电子科技圈3 天前
基于车载SerDes和OpenGMSL协议的SoC设计与验证:行业高频问题解析
设计模式·车载系统·软件构建·设计规范
ClinicTech3 天前
高速冷冻离心机的温控系统与安全保护逻辑解析
设计模式·架构·健康医疗·设计语言