package com.eyugame.modle; /** * 责任链模式 * * @author JYC506 * */ /* 事件接收者 */ public abstract class EventReceiver { private EventReceiver nextEventReceiver; public void setNextHandler(EventReceiver nextEventReceiver) { this.nextEventReceiver = nextEventReceiver; } public Response handleRequest(Request request) { if (this.isOk(request)) { return this.getResponse(); } else { if (this.nextEventReceiver != null) { return this.nextEventReceiver.handleRequest(request); } else { System.out.println("没有合适的事件接收者"); return null; } } } public abstract Response getResponse(); protected abstract boolean isOk(Request request); public static void main(String[] args) { /* 创建一个请求 */ Request request = new Request(Command.EVENT2); /* 非责任链模式下的代码 */ if (request.getCommand() == Command.EVENT1) { new EventReceiver1().handleRequest(request); } else if (request.getCommand() == Command.EVENT2) { new EventReceiver2().handleRequest(request); } else if (request.getCommand() == Command.EVENT3) { new EventReceiver3().handleRequest(request); } else if (request.getCommand() == Command.EVENT4) { new EventReceiver4().handleRequest(request); } /* 责任链模式下的代码 */ /* 是不是责任链模式比较清晰点,低耦合,不过比较耗内存,因为都是提前并全部new出对象 */ EventReceiver receiver1 = new EventReceiver1(); EventReceiver receiver2 = new EventReceiver2(); EventReceiver receiver3 = new EventReceiver3(); EventReceiver receiver4 = new EventReceiver4(); receiver1.setNextHandler(receiver2); receiver2.setNextHandler(receiver3); receiver3.setNextHandler(receiver4); receiver1.handleRequest(request); } } /*返回结果类*/ class Response { } /* 请求 */ class Request { Command command; public Request(Command command) { super(); this.command = command; } public Command getCommand() { return command; } public void setCommand(Command command) { this.command = command; } } /* 请求命令 */ enum Command { EVENT1, EVENT2, EVENT3, EVENT4 } class EventReceiver1 extends EventReceiver { @Override public Response getResponse() { System.out.println("事件处理者1处理并返回结果"); return null; } @Override protected boolean isOk(Request request) { return request.getCommand() == Command.EVENT1; } } class EventReceiver2 extends EventReceiver { @Override public Response getResponse() { System.out.println("事件处理者2处理并返回结果"); return null; } @Override protected boolean isOk(Request request) { return request.getCommand() == Command.EVENT2; } } class EventReceiver3 extends EventReceiver { @Override public Response getResponse() { System.out.println("事件处理者3处理并返回结果"); return null; } @Override protected boolean isOk(Request request) { return request.getCommand() == Command.EVENT3; } } class EventReceiver4 extends EventReceiver { @Override public Response getResponse() { System.out.println("事件处理者4处理并返回结果"); return null; } @Override protected boolean isOk(Request request) { return request.getCommand() == Command.EVENT3; } }
时间: 2024-11-09 03:14:19