Chain Of Responsibility——設計模式學習筆記

來源:互聯網
上載者:User

Chain Of Responsibility

一 意圖

  使多個對象都有機會處理請求,從而避免請求的寄件者和接收者之間的耦合關係。

將這些對象連成一條鏈,並沿著這條鏈傳遞該請求,直到有一個對象處理它為止。

二 動機

這一模式的想法是,給多個對象處理一個請求的機會,從而解耦寄件者和接受者。該請

求沿對象鏈傳遞直至其中一個對象處理它從第一個對象開始,鏈中收到請求的對象要麼親自處理它,

要麼轉寄給鏈中的下一個候選者。提交請求的對象並不明確地知道哪一個對象將會處理它—我們說該請求有一個隱式的接收者(implicit receiver)。

三 適用性及其結構

在以下條件下使用Responsibility 鏈:

• 有多個的對象可以處理一個請求,哪個對象處理該請求運行時刻自動確定。

• 你想在不明確指定接收者的情況下,向多個對象中的一個提交一個請求。

• 可處理一個請求的對象集合應被動態指定。

結構

 

•Handler

— 定義一個處理請求的介面。

— (可選) 實現後繼鏈。

—  m_successor 維護可連結的後繼者。

• ConcreteHandler

— 處理它所負責的請求。

— 可訪問它的後繼者。

— 如果可處理該請求,就處理之;否則將該請求轉寄給它的後繼者。

• Client

—向鏈上的具體處理者對象提交請求。

 

實現後繼連結有很多方式:定義新的串連(Handler中);使用已有的連結(obj->HandleRequest)。

 

四 代碼實現


來自網路的一個例子:

 

基類:
/*----------------------------------------------------------------*/
/* class Base */
/*----------------------------------------------------------------*/
class Base
{
public:
Base()
{
next = 0;
}
void setNext(Base *n)
{
next = n;
}
void add(Base *n)
{
if (next)
{
next->add(n);
}
else
{
next = n;
}
}
virtual void handle(int i)
{
if (next != 0)
{
next->handle(i);
}

}
private:
Base *next;
};

 

子類:

/*----------------------------------------------------------------*/
/* class Handler1 */
/*----------------------------------------------------------------*/
class Handler1: public Base
{
public:
void handle(int i)
{
if (rand() % 3)
{
cout << "H1 passsed " << i << "";
Base::handle(i);
}
else
cout << "H1 handled " << i << "";
}
};
/*----------------------------------------------------------------*/
/* class Handler2 */
/*----------------------------------------------------------------*/
class Handler2: public Base
{
public:
void handle(int i)
{
if (rand() % 3)
{
cout << "H2 passsed " << i << "";
Base::handle(i);
}
else
cout << "H2 handled " << i << "";
}
};
/*----------------------------------------------------------------*/
/* class Handler3 */
/*----------------------------------------------------------------*/
class Handler3: public Base
{
public:
void handle(int i)
{
if (rand() % 3)
{
cout << "H3 passsed " << i << "";
Base::handle(i);
}
else
cout << "H3 handled " << i << "";
}
};

 

Test:

#include "ChainOfResponsibility.h"

int main()
{
srand(time(0));
Handler1 root;
Handler2 two;
Handler3 thr;
root.add(&two);
root.add(&thr);

thr.setNext(&root);
for (int i = 1; i < 10; i++)
{
root.handle(i);
cout << '\n';
}
return 0;
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.