JavaScript设计模式「基于ES2024」:行为型模式-职责链模式

47 阅读2分钟

职责链模式是一种行为设计模式,它允许你将请求沿着处理者链进行发送。收到请求后,每个处理者均可对请求进行处理,或将其传递给链中的下一个处理者。

// 定义支持请求类
class SupportTicket {
    constructor(type, priority, description) {
        this.type = type;
        this.priority = priority;
        this.description = description;
        this.resolved = false;
    }
}

// 抽象处理者类
class SupportHandler {
    #nextHandler;

    setNext(handler) {
        this.#nextHandler = handler;
        return handler;
    }

    handle(ticket) {
        if (this.#nextHandler) {
            return this.#nextHandler.handle(ticket);
        }
        return null;
    }
}

// 具体处理者:一线支持
class FirstLevelSupport extends SupportHandler {
    handle(ticket) {
        if (ticket.priority === 'low') {
            console.log(`First Level Support handling ${ticket.type} ticket: ${ticket.description}`);
            ticket.resolved = true;
            return "First Level Support resolved the issue.";
        }
        return super.handle(ticket);
    }
}

// 具体处理者:二线支持
class SecondLevelSupport extends SupportHandler {
    handle(ticket) {
        if (ticket.priority === 'medium') {
            console.log(`Second Level Support handling ${ticket.type} ticket: ${ticket.description}`);
            ticket.resolved = true;
            return "Second Level Support resolved the issue.";
        }
        return super.handle(ticket);
    }
}

// 具体处理者:高级支持
class AdvancedSupport extends SupportHandler {
    handle(ticket) {
        if (ticket.priority === 'high') {
            console.log(`Advanced Support handling ${ticket.type} ticket: ${ticket.description}`);
            ticket.resolved = true;
            return "Advanced Support resolved the issue.";
        }
        return super.handle(ticket);
    }
}

// 客户支持系统
class CustomerSupportSystem {
    #handler;

    constructor() {
        // 设置处理链
        const firstLevel = new FirstLevelSupport();
        const secondLevel = new SecondLevelSupport();
        const advancedLevel = new AdvancedSupport();

        firstLevel.setNext(secondLevel).setNext(advancedLevel);
        this.#handler = firstLevel;
    }

    submitTicket(ticket) {
        const result = this.#handler.handle(ticket);
        if (result) {
            console.log(result);
        } else {
            console.log("The ticket could not be resolved. Escalating to management.");
        }
    }
}

// 使用示例
function demonstrateChainOfResponsibility() {
    const supportSystem = new CustomerSupportSystem();

    const lowPriorityTicket = new SupportTicket('General Inquiry', 'low', 'How do I reset my password?');
    const mediumPriorityTicket = new SupportTicket('Technical Issue', 'medium', 'My account is locked out.');
    const highPriorityTicket = new SupportTicket('System Outage', 'high', 'The website is down!');
    const unresolvableTicket = new SupportTicket('Unknown Issue', 'critical', 'Strange behavior in the system.');

    console.log("Submitting low priority ticket:");
    supportSystem.submitTicket(lowPriorityTicket);

    console.log("\nSubmitting medium priority ticket:");
    supportSystem.submitTicket(mediumPriorityTicket);

    console.log("\nSubmitting high priority ticket:");
    supportSystem.submitTicket(highPriorityTicket);

    console.log("\nSubmitting unresolvable ticket:");
    supportSystem.submitTicket(unresolvableTicket);
}

demonstrateChainOfResponsibility();

实现思路

  1. SupportTicket

    • 代表客户支持请求,包含类型、优先级和描述等信息。
  2. SupportHandler 类(抽象处理者)

    • 定义了设置下一个处理者和处理请求的接口。
    • 使用私有字段 #nextHandler 来存储下一个处理者。
  3. 具体处理者类(FirstLevelSupport, SecondLevelSupport, AdvancedSupport

    • 继承自 SupportHandler
    • 根据ticket的优先级决定是否处理请求。
    • 如果不能处理,则传递给链中的下一个处理者。
  4. CustomerSupportSystem

    • 设置和维护处理者链。
    • 提供提交ticket的接口。

优点

  • 降低耦合度:发送者不需要知道哪个对象会处理请求。
  • 增加灵活性:可以动态地改变链中的处理者或者他们的顺序。
  • 单一职责原则:每个处理者只负责自己能处理的请求类型。
  • 开闭原则:可以在不修改现有代码的情况下添加新的处理者。