首页 > 代码库 > 责任链模式

责任链模式

  责任链模式:使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这些对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。

  示例图:

技术分享

php代码示例:

<?phpclass Request{    public $tcontent,$tnum;    function __construct($tcontent,$tnum){        $this -> tcontent = $tcontent;        $this -> tnum = $tnum;    }}class Manager{    public $name,$manager;    function __construct($temp){        $this -> name = $temp;    }    function SetSuccessor($temp){        $this -> manager = $temp;    }    function GetRequest($req){    }}class CommonManager extends Manager{    function GetRequest($req){        if($req -> tnum >= 0 && $req -> tnum < 10){            print $this->name." handled ".$req->tnum." request\n";        }else{            $this -> manager -> GetRequest($req);        }    }}class MajorDomo extends Manager{    function GetRequest($req){        if($req -> tnum >= 10){            print $this->name." handled ".$req->tnum." request\n";        }    }}$common = new CommonManager("xiao");$major = new MajorDomo("da");$common -> SetSuccessor($major);$req2 = new Request("salary",3);$common -> GetRequest($req2);$req1 = new Request("vacation",33);$common -> GetRequest($req1);?>

  

责任链模式