责任链模式
作者:互联网
责任链模式
介绍
责任链模式为请求创建了一个接收者对象的链。这种模式给予请求的类型,对请求的发送者和接收者进行解耦。
避免请求发送者与接收者耦合在一起,让多个对象都有可能接收请求,将这些对象连接成一条链,并且沿着这条链传递请求,直到有对象处理它为止。
使用
StateRoadRoadIncidentHandler(省) 《《 MunicipalityRoadRoadIncidentHandler(市) 《《 TownRoadRoadIncidentHandler(镇)
public interface RoadIncidentHandler { void handle(RoadIncident roadIncident); boolean withinBounds(double lat, double lng); }
/** * 省 * */ @Slf4j public class StateRoadRoadIncidentHandler implements RoadIncidentHandler { @Override public void handle(RoadIncident roadIncident) { //经纬度不在该省范围内 if(!withinBounds(roadIncident.getLatitude(),roadIncident.getLatitude())) { throw new IllegalArgumentException("Incident cannot be handled by state. No successor available"); } /** * Handle the incident */ log.info("sheng..."); } @Override public boolean withinBounds(double lat, double lng) { /** * Reverse geolocation, look up by name, radius based distance etc. */ return true; } }
/** * 市 * */ @Slf4j public class MunicipalityRoadRoadIncidentHandler implements RoadIncidentHandler { private final RoadIncidentHandler successor; public MunicipalityRoadRoadIncidentHandler(final RoadIncidentHandler successor) { this.successor = successor; } @Override public void handle(RoadIncident roadIncident) { //经纬度不在该市范围内 if(!withinBounds(roadIncident.getLatitude(),roadIncident.getLongtitude())) { successor.handle(roadIncident); } else { /** * Handle the incident */ log.info("shi..."); } } @Override public boolean withinBounds(double lat, double lng) { /** * Reverse geolocation, look up by name, radius based distance etc. */ return false; } }
/** * 镇 * */ @Slf4j public class TownRoadRoadIncidentHandler implements RoadIncidentHandler { private final RoadIncidentHandler successor; public TownRoadRoadIncidentHandler(final RoadIncidentHandler successor) { this.successor = successor; } @Override public void handle(RoadIncident roadIncident) { //经纬度不在该镇范围内 if(!withinBounds(roadIncident.getLatitude(),roadIncident.getLongtitude())) { successor.handle(roadIncident); } else { /** * Handle the incident */ log.info("zhen..."); } } @Override public boolean withinBounds(double lat, double lng) { /** * Reverse geolocation, look up by name, radius based distance etc. */ return false; } }
将请求发送到职责链上
StateRoadRoadIncidentHandler state = new StateRoadRoadIncidentHandler(); MunicipalityRoadRoadIncidentHandler municipality = new MunicipalityRoadRoadIncidentHandler(state); TownRoadRoadIncidentHandler firstTown = new TownRoadRoadIncidentHandler(municipality); RoadIncident roadIncident = new RoadIncident(0d,0d,"Something happened"); firstTown.handle(roadIncident);
标签:double,模式,责任,roadIncident,withinBounds,successor,public,RoadIncidentHandler 来源: https://www.cnblogs.com/sanqianyuejia/p/15556788.html