分类:
2008-09-12 09:14:50
源自:
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) {
this.hasCar = hasCar;
this.hasHouse = hasHouse;
this.hasResponsibility = hasResponsibility;
}
public boolean isHasCar() {
return hasCar;
}
public void setHasCar(boolean hasCar) {
this.hasCar = hasCar;
}
public boolean isHasHouse() {
return hasHouse;
}
public void setHasHouse(boolean hasHouse) {
this.hasHouse = hasHouse;
}
public boolean isHasResponsibility() {
return hasResponsibility;
}
public void setHasResponsibility(boolean hasResponsibility) {
this.hasResponsibility = hasResponsibility;
}
}
public interface Handler {
public void handleRequest(Boy boy);
}
public class HouseHandler implements Handler {
private Handler handler;
public HouseHandler(Handler handler) {
this.handler = handler;
}
public Handler getHandler() {
return handler;
}
public void setHandler(Handler handler) {
this.handler = handler;
}
public void handleRequest(Boy boy) {
if (boy.isHasHouse()) {
System.out.println("没想到吧,我还有房子");
} else {
System.out.println("我也没有房");
handler.handleRequest(boy);
}
}
}
public class CarHandler implements Handler {
private Handler handler;
public CarHandler(Handler handler) {
this.handler = handler;
}
public Handler getHandler() {
return handler;
}
public void setHandler(Handler handler) {
this.handler = handler;
}
public void handleRequest(Boy boy) {
if (boy.isHasCar()) {
System.out.println("呵呵,我有辆车");
} else {
System.out.println("我没有车");
handler.handleRequest(boy);
}
}
}
public class ResponsibilityHandler implements Handler {
private Handler handler;
public ResponsibilityHandler(Handler handler) {
this.handler = handler;
}
public Handler getHandler() {
return handler;
}
public void setHandler(Handler handler) {
this.handler = handler;
}
public void handleRequest(Boy boy) {
if (boy.isHasResponsibility()) {
System.out.println("我只有一颗带Responsibility的心");
} else {
System.out.println("更没有责任心");
handler.handleRequest(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方法
handler.handleRequest(boy);
}
}