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

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

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

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

相关推荐
xlsw_4 分钟前
java全栈day20--Web后端实战(Mybatis基础2)
java·开发语言·mybatis
神仙别闹1 小时前
基于java的改良版超级玛丽小游戏
java
黄油饼卷咖喱鸡就味增汤拌孜然羊肉炒饭1 小时前
SpringBoot如何实现缓存预热?
java·spring boot·spring·缓存·程序员
暮湫2 小时前
泛型(2)
java
超爱吃士力架2 小时前
邀请逻辑
java·linux·后端
南宫生2 小时前
力扣-图论-17【算法学习day.67】
java·学习·算法·leetcode·图论
转码的小石2 小时前
12/21java基础
java
李小白662 小时前
Spring MVC(上)
java·spring·mvc
GoodStudyAndDayDayUp2 小时前
IDEA能够从mapper跳转到xml的插件
xml·java·intellij-idea
装不满的克莱因瓶3 小时前
【Redis经典面试题六】Redis的持久化机制是怎样的?
java·数据库·redis·持久化·aof·rdb