行为型-责任链模式

# 行为型-责任链模式

用于在条件判断很多的时候。

<template>
  <button @click="handleClick">抽奖</button>
</template>

<script>
export default {
  data() {
    return {
      condition1: false,
      condition2: true,
      // 其他条件...
    };
  },
  methods: {
    handleClick() {
      const handler1 = new Condition1Handler(this.condition1);
      const handler2 = new Condition2Handler(this.condition2);
      // 设置责任链
      handler1.setNext(handler2);
      // 开始处理
      handler1.handle();
    },
  },
};

class Handler {
  constructor(condition) {
    this.condition = condition;
  }
  setNext(handler) {
    this.next = handler;
  }
  handle() {
    if (this.next) {
      return this.next.handle();
    }
    return null;
  }
}

class Condition1Handler extends Handler {
  handle() {
    if (this.condition) {
      // 处理请求
      console.log("Condition 1 met, processing...");
    } else if (this.next) {
      return this.next.handle();
    }
  }
}

class Condition2Handler extends Handler {
  handle() {
    if (this.condition) {
      // 处理请求
      console.log("Condition 2 met, processing...");
    } else if (this.next) {
      return this.next.handle();
    }
  }
}
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
Last Updated: 9/25/2026, 2:08:32 PM