//接口Request拥有getType与execute方法
public class RequestStudent implements Request{
//handlerRequest是接口Handler 的方法
public class HandlerStudent implements Handler {
public HandlerStudent(Handler nextSuccessor){
this.nextSuccessor = nextSuccessor; }
public void handlerRequest(Request request) {
// 处理StudentRequest
if(request.getType().equalsIgnoreCase("StudentRequest")){
System.out.println("HandlerStudent begin to response StudentRequest;");
request.execute(); }
else{
//把请求传递给其他受理者
if(this.nextSuccessor!=null){
nextSuccessor.handlerRequest(request); }
else{
System.out.println("request[" + request.getType() + "] has not handler to deal!"); } } } }
//测试类
public class Test { public static void main(String[] args) {
Handler handler = new HandlerStudent(new HandlerTeacher(new HandlerSchoolmaster(null)));
Request studentReq = new RequestStudent();
Request teacherReq = new RequestTeacher();
Request schoolmasterReq = new RequestSchoolmaster();
Request presidentReq = new RequestPresident();
//传入student request
handler.handlerRequest(studentReq);
System.out.println("=========");
//传入teacher request
handler.handlerRequest(teacherReq);
System.out.println("=========");
//传入schoolmaster request
handler.handlerRequest(schoolmasterReq);
System.out.println("=========");
//传入president request
handler.handlerRequest(presidentReq);
System.out.println("========="); } }