【设计模式】职责链模式

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

<!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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

秀秀_heo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值