标签:
在平时的生活中,小伙伴们一起共事,经常在遇到问题时会甩锅,但是最终总是有人要背锅的,当然就是这件事的负责人了(虽然可能有时候是无辜的),但是锅是要背的,23333,那么我们来看看甩锅这段程序如何用责任链模式实现:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by liulin on 16-4-26.
*/
class ErrorRequester{
//标记请求的类型
private String duty;
public String getDuty() {
return duty;
}
public void setDuty(String duty) {
this.duty = duty;
}
}
abstract class Handler{
//记录当前责任链的下一个元素
private Handler nextHandler;
//标记当前子类的类型
private String duty;
public static final String DBA="SQL and the database";
public static final String FRONT="HTML and CSS";
public static final String BGD="Java and XML";
//方便子类设置自己的类型(子类通过无参数的构造器隐藏该实现)
public Handler ( String duty ){
this.duty = duty;
}
//责任链的职责传递逻辑的实现,不支持子类的覆盖
public final void handleMessage ( ErrorRequester requester ){
if( requester.getDuty().equals(duty)){
response( requester);
}else{
if( nextHandler != null ){
nextHandler.handleMessage( requester );
}else{
System.out.println("The Error is due to others!!!");
}
}
}
public final void setNextHandler( Handler handler ){
nextHandler = handler;
}
//TODO 匹配到合适的类型时的,回应请求的函数
protected abstract void response( ErrorRequester requester );
}
class DBAHandler extends Handler{
//设置当前子类的处理器类型
public DBAHandler() {
super( Handler.DBA);
}
//如果当前类型匹配上,那么进行响应
@Override
protected void response(ErrorRequester requester) {
System.out.println( "What horrible "+ requester.getDuty() + " is!!!!");
}
}
class BGDHandler extends Handler{
public BGDHandler() {
super(Handler.BGD);
}
@Override
protected void response(ErrorRequester requester) {
System.out.println("What horrible " + requester.getDuty() + " is!!!");
}
}
class FRONTHandler extends Handler{
public FRONTHandler() {
super(Handler.FRONT);
}
@Override
protected void response(ErrorRequester requester) {
System.out.println("What horrible " + requester.getDuty() + " is!!!");
}
}
public class CORTest {
public static void main ( String [] args ){
//构造词典
HashMap<Integer,String> dic = new HashMap();
dic.put ( 0 , Handler.DBA );
dic.put ( 1 , Handler.BGD );
dic.put ( 2 , Handler.FRONT);
int times = 0;
//建立责任链
Handler dba = new DBAHandler();
Handler bgd = new BGDHandler();
Handler front = new FRONTHandler();
dba.setNextHandler( bgd );
bgd.setNextHandler( front );
//生成随机的请求,并且响应
while ( times++ != 10 ){
ErrorRequester requester = new ErrorRequester();
requester.setDuty( dic.get((int)(Math.random()*100)%3) );
dba.handleMessage( requester );
}
}
}
Tomcat的容器设置就是责任链模式,从Engine到Host再到Context一知道Wraper都通过一个链传递请求。
Java设计模式(七) COR(责任链)模式及Tomcat引申
标签:
原文地址:http://blog.csdn.net/qq_24451605/article/details/51253063