【设计模式】职责链模式

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

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>
相关推荐
丶白泽42 分钟前
重修设计模式-结构型-装饰器模式
java·设计模式·装饰器模式
WineMonk1 小时前
设计模式 23 访问者模式
设计模式·访问者模式
WineMonk10 小时前
设计模式 21 策略模式
设计模式·策略模式
AI让世界更懂你13 小时前
漫谈设计模式 [13]:命令模式
python·设计模式·命令模式
心之语歌1 天前
设计模式 装饰模式(Decorator Pattern)
java·设计模式·装饰器模式
程序员与背包客_CoderZ1 天前
C++设计模式——Iterator迭代器模式
linux·c语言·开发语言·c++·设计模式·迭代器模式
程序员与背包客_CoderZ1 天前
C++设计模式——Memento备忘录模式
linux·c语言·开发语言·c++·设计模式·备忘录模式
anyup_前端梦工厂1 天前
JS设计模式之外观模式:简化复杂系统调用的利器
前端·javascript·设计模式
动物园首领1 天前
Java 设计模式-状态模式
java·设计模式·状态模式
程序员与背包客_CoderZ1 天前
C++设计模式——State状态模式
c语言·开发语言·c++·设计模式·状态模式