設計模式-行爲型之責任鏈(responsibility)模式

定義

  • 將不能處理的事情交給別人去處理。

使用場景

  • 弱化請求者與處理者的關係。
  • 舉例:審批鏈:三天內假直系領導審批,七天內假期副總審批,兩週內總經理審批。

UML圖

在這裏插入圖片描述

代碼實現

// 抽象責任者
public abstract class Handler {

    private Handler next;

    //設置下一個處理者:取一下巧,返回nxet
    public Handler setNext(Handler next){
        this.next = next;
        return next;
    }

    public void doResolve(Integer vacation){
        if(resolve(vacation)){
            System.out.println("審批成功");
        }else if(next != null){
        	//交給下一個人處理
            next.doResolve(vacation);
        }else {
            System.out.println("審批未通過");
        }
    }

    //處理方法: protected 由子類提供實現
    protected abstract boolean resolve(Integer vacation);
}
//具體處理者
public class LeadHandler extends Handler {

    @Override
    public boolean resolve(Integer vacation) {
        if(vacation <= 3 && vacation > 0){
            System.out.println("直系領導同意!");
            return true;
        }
        return false;
    }
}
//具體處理者
public class ManagerHandler extends Handler {
    @Override
    protected boolean resolve(Integer vacation) {
        if(vacation <= 7){
            System.out.println("經理同意");
            return true;
        }
        return false;
    }
}
//具體處理者
public class BossHandler extends Handler {
    @Override
    protected boolean resolve(Integer vacation) {
        if(vacation <= 14){
            System.out.println("老闆同意");
            return true;
        }
        return false;
    }
}
//請求者
public class Client {
    public static void main(String[] args) {
        Handler handler = new LeadHandler();
        handler.setNext(new ManagerHandler()).setNext(new BossHandler());
        handler.doResolve(7);
        handler.doResolve(10);
        handler.doResolve(16);
    }
}

總結

  • 將不能處理的事情交給別人去處理。各個對象專注於自己的事情。
  • 符合里氏替換原則,職責鏈的下一級可以動態變換。
  • 弱化請求者與處理者的關係是一個好處,同時也會帶來處理延遲。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章