探索Java设计模式:责任链模式

时间:2024-04-27 12:12:04
// 定义抽象审批人接口,包含处理请求的方法 interface Approver { void setNext(Approver approver); void processRequest(Request request); } // 具体审批人角色实现 class Manager implements Approver { private Approver nextApprover; @Override public void setNext(Approver approver) { this.nextApprover = approver; } @Override public void processRequest(Request request) { if (request.getAmount() <= 5000) { System.out.println("Manager approved request: " + request.getDescription()); } else if (nextApprover != null) { nextApprover.processRequest(request); } else { System.out.println("No one can approve this request."); } } } class Director implements Approver { private Approver nextApprover; @Override public void setNext(Approver approver) { this.nextApprover = approver; } @Override public void processRequest(Request request) { if (request.getAmount() <= 10000) { System.out.println("Director approved request: " + request.getDescription()); } else if (nextApprover != null) { nextApprover.processRequest(request); } else { System.out.println("No one can approve this request."); } } } class President implements Approver { private Approver nextApprover; @Override public void setNext(Approver approver) { this.nextApprover = approver; } @Override public void processRequest(Request request) { if (request.getAmount() <= 20000) { System.out.println("President approved request: " + request.getDescription()); } else { System.out.println("Request exceeds the president's authority."); } } } // 请求类 class Request { private String description; private int amount; public Request(String description, int amount) { this.description = description; this.amount = amount; } // ... getters and setters }