?
essage从第一个链开始判断和处理,如果不能处理就传给下一个链,每一个链用handler表示。所有的链继承自同一个父类,Handler
?
使多个对象都有机会处理请求,从而避免请求的?发送者和接受者之间的耦合。将这些对象连成一个链,并按着这个链传递该请求,直到有一个对象处理他为止
?
public class Test {
?public static void main(String[] args) {
??
??Handler h1 = new BuyGoodsHandler();
??Handler h2 = new PayMoneyHandler();
??Handler h3 = new LogHandler();
??
??h1.setNextHandler(h2);
??h2.setNextHandler(h3);
??h2.setPreHandler(h1);
??
??Customer c = new Customer("lisi", h1);
??c.buy();
?}
?static class Customer{
??
??private String name;
??private Handler h;
??
??public Customer(String name, Handler h){
???this.name = name;
???this.h = h;
??}
??
??public void buy(){
???h.doHandler();
??}
?}
}
?
//买东西--付钱--记日志
public class BuyGoodsHandler implements Handler {
?
?private Handler nextHandler;
?public void doHandler() {
??try{
???System.out.println("1.买东西");
???//测试回退
//???int i=0;
//???i = 1/i;
???nextHandler.doHandler();
??}catch(Exception e){
???rollback();
??}
?}
?public void rollback() {
??System.out.println("1.回退");
?}
?public void setNextHandler(Handler nextHandler) {
??this.nextHandler = nextHandler;
?}
?public void setPreHandler(Handler preHandler) {
??
?}
}
?
public interface Handler {
?//业务处理
?void doHandler();
?//业务回退
?void rollback();
?
?void setPreHandler(Handler preHandler);
?
?void setNextHandler(Handler nexHandler);
}
?
public class LogHandler implements Handler {
?private Handler preHandler;
?
?public void doHandler() {
??try{
???System.out.println("3.记录日志");
???int i = 0;
???i = 1/i;
??}catch(Exception e){
???rollback();
??}
?}
?public void rollback() {
??System.out.println("3.回退");
??this.preHandler.rollback();
?}
?public void setPreHandler(Handler preHandler) {
??this.preHandler = preHandler;
?}
?public void setNextHandler(Handler nexHandler) {
??
?}
}
?
public class PayMoneyHandler implements Handler {
?private Handler preHandler;
?private Handler nextHandler;
?
?public void doHandler() {
??try{
???System.out.println("2.付钱");
//???int i=0;
//???i = 1/i;
???this.nextHandler.doHandler();
??}catch(Exception e){
???rollback();
??}
?}
?public void rollback() {
??System.out.println("2.回退");
??this.preHandler.rollback();
?}
?public void setPreHandler(Handler preHandler) {
??this.preHandler = preHandler;
??preHandler.setNextHandler(this);
?}
?public void setNextHandler(Handler nextHandler) {
??this.nextHandler = nextHandler;
??nextHandler.setPreHandler(this);
?}
}
?