【设计模式】职责链模式

卖不甜枣  论坛元老 | 2024-8-28 05:21:41 | 来自手机 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 1043|帖子 1043|积分 3129

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
使多个对象都有机会处理请求,从而避免了请求的发送者与多个接收者直接的耦合关系,将这些接收者毗连成一条链,顺着这条链通报该请求,直到找到能处理该请求的对象。
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <title>Title</title>
  6. </head>
  7. <body>
  8. <input type="text" id="input">
  9. <button id="button">注册</button>
  10. <script>
  11.     function checkEmpty() {
  12.         if (input.value.length === 0) {
  13.             alert('不能为空');
  14.             return false;
  15.         } else {
  16.             return true;
  17.         }
  18.     }
  19.     function checkLength() {
  20.         if (input.value.length < 6) {
  21.             alert('长度不能小于6');
  22.             return false;
  23.         } else {
  24.             return true;
  25.         }
  26.     }
  27.     class Chain{
  28.         constructor(fn) {
  29.             this.fn = fn;
  30.             this.next = null;
  31.         }
  32.         setNext(next) {
  33.             this.next = next;
  34.         }
  35.         run() {
  36.             let result = this.fn.apply(this, arguments);
  37.             if (result === true && this.next !== null) {
  38.                 return this.next.run.apply(this.next, arguments);
  39.             }
  40.             return result;
  41.         }
  42.     }
  43.     let chain1 = new Chain(checkEmpty);
  44.     let chain2 = new Chain(checkLength);
  45.     chain1.setNext(chain2);
  46.     button.onclick = function () {
  47.         chain1.run();
  48.     }
  49. </script>
  50. </body>
  51. </html>
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

卖不甜枣

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表