1、问题描述
小明所在的公司请假需要在OA系统上发布申请,整个请求流程包括多个处理者,每个处理者负责处理不同范围的请假天数,如果一个处理者不能处理请求,就会将请求传递给下一个处理者,请你实现责任链模式,可以根据请求天数找到对应的处理者。
审批责任链由主管(Supervisor), 经理(Manager)和董事(Director)组成,他们分别能够处理3天、7天和10天的请假天数。如果超过10天,则进行否决。
输入示例
4
Alice 2
Bob 5
Tom 10
Jerry 12
输出示例
Alice Approved by Supervisor.
Bob Approved by Manager.
Tom Approved by Director.
Jerry Denied by Director.文章来源:https://www.toymoban.com/news/detail-859350.html
2、责任链模式
其实就是单链表数据结构,一个个递归向后处理,当前节点能处理就返回
文章来源地址https://www.toymoban.com/news/detail-859350.html
3、代码
import com.sun.java.accessibility.util.TopLevelWindowListener;
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
Supervisor s=new Supervisor();
Manager m=new Manager();
Director d=new Director();
s.setNext(m);
m.setNext(d);
int number=Integer.parseInt(sc.nextLine());
for(int i=0;i<number;i++){
String input=sc.nextLine();
String[] ss=input.split(" ");
String username=ss[0];
int day=Integer.parseInt(ss[1]);
s.handleRequest(username,day);
}
}
}
interface Handler{
void setNext(Handler next);
Handler getNext();
void handleRequest(String username,int time);
boolean canHandleRequest(int time);
}
class Supervisor implements Handler{
private Handler next;
@Override
public void setNext(Handler next) {
this.next=next;
}
@Override
public Handler getNext() {
return this.next;
}
@Override
public void handleRequest(String username,int time) {
if(canHandleRequest(time)){
System.out.println(username+" Approved by Supervisor.");
}else {
Handler next=getNext();
next.handleRequest(username,time);
}
}
@Override
public boolean canHandleRequest(int time) {
if(time>3){
return false;
}
return true;
}
}
class Manager implements Handler{
private Handler next;
@Override
public void setNext(Handler next) {
this.next=next;
}
@Override
public Handler getNext() {
return this.next;
}
@Override
public void handleRequest(String username, int time) {
if(canHandleRequest(time)){
System.out.println(username+" Approved by Manager.");
}else {
Handler next=getNext();
next.handleRequest(username,time);
}
}
@Override
public boolean canHandleRequest(int time) {
if(time>5){
return false;
}
return true;
}
}
class Director implements Handler{
private Handler next;
@Override
public void setNext(Handler next) {
this.next=next;
}
@Override
public Handler getNext() {
return this.next;
}
@Override
public void handleRequest(String username, int time) {
if(canHandleRequest(time)){
System.out.println(username+" Approved by Director.");
}else {
System.out.println(username+" Denied by Director.");
}
}
@Override
public boolean canHandleRequest(int time) {
if(time>10){
return false;
}
return true;
}
}
到了这里,关于设计模式代码实战-责任链模式的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!