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

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

示例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);
    }
}

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

相关推荐
草莓base12 分钟前
【手写一个spring】spring源码的简单实现--容器启动
java·后端·spring
Allen Bright25 分钟前
maven概述
java·maven
编程重生之路28 分钟前
Springboot启动异常 错误: 找不到或无法加载主类 xxx.Application异常
java·spring boot·后端
薯条不要番茄酱28 分钟前
数据结构-8.Java. 七大排序算法(中篇)
java·开发语言·数据结构·后端·算法·排序算法·intellij-idea
努力进修37 分钟前
“探索Java List的无限可能:从基础到高级应用“
java·开发语言·list
politeboy38 分钟前
k8s启动springboot容器的时候,显示找不到application.yml文件
java·spring boot·kubernetes
Daniel 大东1 小时前
BugJson因为json格式问题OOM怎么办
java·安全
哪 吒6 小时前
最简单的设计模式,抽象工厂模式,是否属于过度设计?
设计模式·抽象工厂模式
Theodore_10226 小时前
4 设计模式原则之接口隔离原则
java·开发语言·设计模式·java-ee·接口隔离原则·javaee
冰帝海岸7 小时前
01-spring security认证笔记
java·笔记·spring