请解释责任链模式与策略模式之间的区别,并举例说明各自的适用场景。

责任链模式和策略模式是两种常用的设计模式,它们的主要区别在于解决的问题和设计思想的不同。以下是它们的详细解释、区别以及适用场景的示例。

责任链模式(Chain of Responsibility Pattern)

责任链模式是一种行为设计模式,允许将请求沿着处理链传递,直到有一个处理者能够处理该请求为止。每个处理者决定是否处理请求,或者将其传递给链中的下一个处理者。

适用场景

责任链模式适用于以下场景:

  1. 需要避免请求发送者和多个请求处理者之间的耦合。
  2. 多个对象可以处理同一请求,但具体由哪个对象处理需要在运行时动态决定。
  3. 请求的处理可能依赖于多个条件,或者需要动态调整责任链的顺序。

示例

例如,一个公司的审批流程中,员工的报销请求可能需要经过多个层级的审批:

  1. 直接主管审批(金额小于 500 元的报销)。
  2. 部门经理审批(金额大于 500 元但小于 5000 元的报销)。
  3. 财务总监审批(金额大于 5000 元的报销)。

如果直接主管无法处理,则会将请求传递给部门经理;如果部门经理也无法处理,则传递给财务总监。

abstract class Approver {
    protected Approver nextApprover;

    public void setNextApprover(Approver nextApprover) {
        this.nextApprover = nextApprover;
    }

    public abstract void handleRequest(int amount);
}

class Manager extends Approver {
    @Override
    public void handleRequest(int amount) {
        if (amount < 500) {
            System.out.println("Manager approves the request.");
        } else if (nextApprover != null) {
            nextApprover.handleRequest(amount);
        }
    }
}

class Director extends Approver {
    @Override
    public void handleRequest(int amount) {
        if (amount < 5000) {
            System.out.println("Director approves the request.");
        } else if (nextApprover != null) {
            nextApprover.handleRequest(amount);
        }
    }
}

class CFO extends Approver {
    @Override
    public void handleRequest(int amount) {
        System.out.println("CFO approves the request.");
    }
}

// 使用示例
Manager manager = new Manager();
Director director = new Director();
CFO cfo = new CFO();

manager.setNextApprover(director);
director.setNextApprover(cfo);
manager.handleRequest(10000); // CFO approves the request.

策略模式(Strategy Pattern)

策略模式是一种行为设计模式,定义了一系列算法,并将每个算法封装起来,使它们可以互相替换。策略模式让算法的变化独立于使用算法的客户。

适用场景

策略模式适用于以下场景:

  1. 系统需要在多种算法中选择一种,且这些算法可以互相替换。
  2. 不希望使用复杂的条件语句来区分多种算法。
  3. 需要在运行时动态切换算法。

示例

例如,电商平台根据不同的促销策略(满减、折扣、无优惠)计算最终价格:

interface PricingStrategy {
    double calculatePrice(double originalPrice);
}

class NoDiscountStrategy implements PricingStrategy {
    @Override
    public double calculatePrice(double originalPrice) {
        return originalPrice;
    }
}

class DiscountStrategy implements PricingStrategy {
    private double discountRate;

    public DiscountStrategy(double discountRate) {
        this.discountRate = discountRate;
    }

    @Override
    public double calculatePrice(double originalPrice) {
        return originalPrice * (1 - discountRate);
    }
}

class FullReductionStrategy implements PricingStrategy {
    private double threshold;
    private double reduction;

    public FullReductionStrategy(double threshold, double reduction) {
        this.threshold = threshold;
        this.reduction = reduction;
    }

    @Override
    public double calculatePrice(double originalPrice) {
        return originalPrice >= threshold ? originalPrice - reduction : originalPrice;
    }
}

class ShoppingCart {
    private PricingStrategy strategy;

    public void setStrategy(PricingStrategy strategy) {
        this.strategy = strategy;
    }

    public double checkout(double originalPrice) {
        return strategy.calculatePrice(originalPrice);
    }
}

// 使用示例
ShoppingCart cart = new ShoppingCart();
cart.setStrategy(new DiscountStrategy(0.2)); // 设置折扣策略
System.out.println(cart.checkout(100)); // 输出 80.0

区别总结

  1. 设计目标不同:

    • 责任链模式的目标是解耦请求发送者和多个请求处理者,动态传递请求。
    • 策略模式的目标是封装多种算法,并在运行时动态选择或替换算法。
  2. 处理方式不同:

    • 责任链模式可能由多个处理者共同处理一个请求(链式传递)。
    • 策略模式通常只有一个策略处理请求(算法替换)。
  3. 适用场景不同:

    • 责任链模式更适合需要动态调整处理顺序或需要多级审批的场景。
    • 策略模式更适合需要多种算法灵活切换的场景。

两种模式的选择取决于具体的业务需求和解耦的目标。