【设计模式】职责链模式

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

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>
相关推荐
数据智能老司机3 小时前
精通 Python 设计模式——创建型设计模式
python·设计模式·架构
数据智能老司机4 小时前
精通 Python 设计模式——SOLID 原则
python·设计模式·架构
烛阴7 小时前
【TS 设计模式完全指南】懒加载、缓存与权限控制:代理模式在 TypeScript 中的三大妙用
javascript·设计模式·typescript
李广坤8 小时前
工厂模式
设计模式
幂简集成explinks1 天前
e签宝签署API更新实战:新增 signType 与 FDA 合规参数配置
后端·设计模式·开源
大飞pkz1 天前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
努力也学不会java1 天前
【设计模式】抽象工厂模式
java·设计模式·oracle·抽象工厂模式
青草地溪水旁1 天前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(2)
c++·设计模式·抽象工厂模式
青草地溪水旁1 天前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(1)
c++·设计模式·抽象工厂模式
Magnetic_h2 天前
【iOS】设计模式复习
笔记·学习·ios·设计模式·objective-c·cocoa