设计模式代码实战-责任链模式
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;
}
}