源自
Chain of Responsibility职责链模式
为了避免请求的发送者和接收者之间的耦合关系使多个接受对象都有机会处理请求将这些对象连成一条链并沿着这条链传递该请求直到有一个对象处理它为止
例子
view plaincopy to clipboardprint?
public class Boy {
private boolean hasCar; // 是否有车
private boolean hasHouse; // 是否有房
private boolean hasResponsibility; // 是否有责任心
public Boy() {
}
public Boy(boolean hasCar boolean hasHouse boolean hasResponsibility) {
thishasCar = hasCar;
thishasHouse = hasHouse;
thishasResponsibility = hasResponsibility;
}
public boolean isHasCar() {
return hasCar;
}
public void setHasCar(boolean hasCar) {
thishasCar = hasCar;
}
public boolean isHasHouse() {
return hasHouse;
}
public void setHasHouse(boolean hasHouse) {
thishasHouse = hasHouse;
}
public boolean isHasResponsibility() {
return hasResponsibility;
}
public void setHasResponsibility(boolean hasResponsibility) {
thishasResponsibility = hasResponsibility;
}
}
public interface Handler {
public void handleRequest(Boy boy);
}
public class HouseHandler implements Handler {
private Handler handler;
public HouseHandler(Handler handler) {
thishandler = handler;
}
public Handler getHandler() {
return handler;
}
public void setHandler(Handler handler) {
thishandler = handler;
}
public void handleRequest(Boy boy) {
if (boyisHasHouse()) {
Systemoutprintln(没想到吧我还有房子);
} else {
Systemoutprintln(我也没有房);
handlerhandleRequest(boy);
}
}
}
public class CarHandler implements Handler {
private Handler handler;
public CarHandler(Handler handler) {
thishandler = handler;
}
public Handler getHandler() {
return handler;
}
public void setHandler(Handler handler) {
thishandler = handler;
}
public void handleRequest(Boy boy) {
if (boyisHasCar()) {
Systemoutprintln(呵呵我有辆车);
} else {
Systemoutprintln(我没有车);
handlerhandleRequest(boy);
}
}
}
public class ResponsibilityHandler implements Handler {
private Handler handler;
public ResponsibilityHandler(Handler handler) {
thishandler = handler;
}
public Handler getHandler() {
return handler;
}
public void setHandler(Handler handler) {
thishandler = handler;
}
public void handleRequest(Boy boy) {
if (boyisHasResponsibility()) {
Systemoutprintln(我只有一颗带Responsibility的心);
} else {
Systemoutprintln(更没有责任心);
handlerhandleRequest(boy);
}
}
}
public class Girl {
public static void main(String[] args) {
Boy boy = new Boy(false false true);// 这个boy没有车也没有房不过很有责任心
Handler handler = new CarHandler(new HouseHandler(
new ResponsibilityHandler(null)));// 也可以使用setHanlder方法
handlerhandleRequest(boy);
}
}