源自
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
this
this
this
}
public boolean isHasCar() {
return hasCar;
}
public void setHasCar(boolean hasCar) {
this
}
public boolean isHasHouse() {
return hasHouse;
}
public void setHasHouse(boolean hasHouse) {
this
}
public boolean isHasResponsibility() {
return hasResponsibility;
}
public void setHasResponsibility(boolean hasResponsibility) {
this
}
}
public interface Handler {
public void handleRequest(Boy boy);
}
public class HouseHandler implements Handler {
private Handler handler;
public HouseHandler(Handler handler) {
this
}
public Handler getHandler() {
return handler;
}
public void setHandler(Handler handler) {
this
}
public void handleRequest(Boy boy) {
if (boy
System
} else {
System
handler
}
}
}
public class CarHandler implements Handler {
private Handler handler;
public CarHandler(Handler handler) {
this
}
public Handler getHandler() {
return handler;
}
public void setHandler(Handler handler) {
this
}
public void handleRequest(Boy boy) {
if (boy
System
} else {
System
handler
}
}
}
public class ResponsibilityHandler implements Handler {
private Handler handler;
public ResponsibilityHandler(Handler handler) {
this
}
public Handler getHandler() {
return handler;
}
public void setHandler(Handler handler) {
this
}
public void handleRequest(Boy boy) {
if (boy
System
} else {
System
handler
}
}
}
public class Girl {
public static void main(String[] args) {
Boy boy = new Boy(false
Handler handler = new CarHandler(new HouseHandler(
new ResponsibilityHandler(null)));// 也可以使用setHanlder方法
handler
}
}
From:http://tw.wingwit.com/Article/program/Java/hx/201311/26552.html