设计模式:责任链模式示例

责任链模式可以应用于多种场景,下面是几个不同场景的例子,每个例子都包括完整的代码。

示例1:日志处理系统

在日志处理系统中,日志消息可以根据其严重性(错误、警告、信息)被不同级别的日志处理器处理。

java 复制代码
abstract class Logger {
    public static int INFO = 1;
    public static int DEBUG = 2;
    public static int ERROR = 3;

    protected int level;
    protected Logger nextLogger;

    public void setNextLogger(Logger nextLogger) {
        this.nextLogger = nextLogger;
    }

    public void logMessage(int level, String message) {
        if (this.level <= level) {
            write(message);
        }
        if (nextLogger != null) {
            nextLogger.logMessage(level, message);
        }
    }

    abstract protected void write(String message);
}

class ConsoleLogger extends Logger {
    public ConsoleLogger(int level) {
        this.level = level;
    }

    @Override
    protected void write(String message) {
        System.out.println("Standard Console::Logger: " + message);
    }
}

class ErrorLogger extends Logger {
    public ErrorLogger(int level) {
        this.level = level;
    }

    @Override
    protected void write(String message) {
        System.err.println("Error Console::Logger: " + message);
    }
}

class FileLogger extends Logger {
    public FileLogger(int level) {
        this.level = level;
    }

    @Override
    protected void write(String message) {
        System.out.println("File::Logger: " + message);
    }
}

public class ChainPatternDemo {
    private static Logger getChainOfLoggers() {
        Logger errorLogger = new ErrorLogger(Logger.ERROR);
        Logger fileLogger = new FileLogger(Logger.DEBUG);
        Logger consoleLogger = new ConsoleLogger(Logger.INFO);

        errorLogger.setNextLogger(fileLogger);
        fileLogger.setNextLogger(consoleLogger);

        return errorLogger;
    }

    public static void main(String[] args) {
        Logger loggerChain = getChainOfLoggers();

        loggerChain.logMessage(Logger.INFO, "This is an information.");
        loggerChain.logMessage(Logger.DEBUG, "This is a debug level information.");
        loggerChain.logMessage(Logger.ERROR, "This is an error information.");
    }
}

示例2:支付处理系统

在一个支付处理系统中,一个支付请求可以通过多种支付方式进行处理。

java 复制代码
abstract class PaymentHandler {
    protected PaymentHandler successor;

    public void setSuccessor(PaymentHandler successor) {
        this.successor = successor;
    }

    public abstract void handlePayment(PaymentRequest request);
}

class PaymentRequest {
    private double amount;

    public PaymentRequest(double amount) {
        this.amount = amount;
    }

    public double getAmount() {
        return amount;
    }
}

class PaypalHandler extends PaymentHandler {
    @Override
    public void handlePayment(PaymentRequest request) {
        if (request.getAmount() < 1000) {
            System.out.println("Paypal processed $" + request.getAmount());
        } else if (successor != null) {
            successor.handlePayment(request);
        }
    }
}

class CreditCardHandler extends PaymentHandler {
    @Override
    public void handlePayment(PaymentRequest request) {
        if (request.getAmount() < 5000) {
            System.out.println("Credit Card processed $" + request.getAmount());
        } else if (successor != null) {
            successor.handlePayment(request);
        }
    }
}

class BankTransferHandler extends PaymentHandler {
    @Override
    public void handlePayment(PaymentRequest request) {
        System.out.println("Bank Transfer processed $" + request.getAmount());
    }
}

public class PaymentChainDemo {
    public static void main(String[] args) {
        PaymentHandler paypal = new PaypalHandler();
        PaymentHandler creditCard = new CreditCardHandler();
        PaymentHandler bankTransfer = new BankTransferHandler();

        paypal.setSuccessor(creditCard);
        creditCard.setSuccessor(bankTransfer);

        PaymentRequest request = new PaymentRequest(450);
        paypal.handlePayment(request);

        request = new PaymentRequest(1200);
        paypal.handlePayment(request);

        request = new PaymentRequest(6500);
        paypal.handlePayment(request);
    }
}

责任链模式在软件设计中非常通用,并且可以在许多不同的场景中找到应用。这些示例展示了责任链模式在处理具有不同处理级别或条件的请求时的灵活性和可扩展性。在实际应用中,责任链模式可以帮助我们创建更加模块化和可管理的代码,但也需要注意不要过度使用,避免不必要的复杂性。

相关推荐
九圣残炎23 分钟前
【从零开始的LeetCode-算法】1456. 定长子串中元音的最大数目
java·算法·leetcode
wclass-zhengge26 分钟前
Netty篇(入门编程)
java·linux·服务器
Re.不晚1 小时前
Java入门15——抽象类
java·开发语言·学习·算法·intellij-idea
雷神乐乐1 小时前
Maven学习——创建Maven的Java和Web工程,并运行在Tomcat上
java·maven
码农派大星。1 小时前
Spring Boot 配置文件
java·spring boot·后端
顾北川_野1 小时前
Android 手机设备的OEM-unlock解锁 和 adb push文件
android·java
江深竹静,一苇以航1 小时前
springboot3项目整合Mybatis-plus启动项目报错:Invalid bean definition with name ‘xxxMapper‘
java·spring boot
confiself1 小时前
大模型系列——LLAMA-O1 复刻代码解读
java·开发语言
Wlq04152 小时前
J2EE平台
java·java-ee
XiaoLeisj2 小时前
【JavaEE初阶 — 多线程】Thread类的方法&线程生命周期
java·开发语言·java-ee