【设计模式】职责链模式

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

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 小时前
RAG 系统进化论(七):Multimodal RAG(多模态 RAG),当知识存在于表格、图片和页面中
人工智能·后端·设计模式
大山同学9 小时前
第 2 篇(03-04 章):代理设计原则与工具使用设计模式
设计模式
啦啦啦啦啦zzzz1 天前
设计模式:桥接模式和组合模式
c++·设计模式·组合模式·桥接模式
莫得感情 o2 天前
设计模式 03 · 工厂方法模式
设计模式·工厂方法模式
cyforkk2 天前
高并发核心设计模式:Single-Flight 原理与实战
设计模式
饼干哥哥2 天前
字节Seedance2.5终于上线,这次在收割谁?
人工智能·设计模式·前端框架
董员外2 天前
RAG 系统进化论(六):GraphRAG(基于知识图谱的 RAG),从相似文本走向实体关系
人工智能·后端·设计模式
鬼鬼鬼2 天前
从 Prompt 到 Harness:企业级 Agent 工程的完整演进之路
设计模式·架构·ai编程
啦啦啦啦啦zzzz2 天前
设计模式:原型模式
c++·设计模式·原型模式
董员外2 天前
RAG 系统进化论(五):Corrective RAG 与 Self-RAG,让系统发现并纠正错误
人工智能·后端·设计模式