設計模式 責任鏈模式

2021-08-09 16:48:40 字數 1858 閱讀 1161

責任鏈模式(chain ofresponsibility pattern)

基本概念:

責任鏈,顧名思義,是指乙個負責相應請求的行為鏈。

首先要理解的是乙個鏈,然後通過這個鏈來管理個行為。

什麼時候會用到責任鏈:

對於乙個請求,沒有特別指明由誰處理或沒有指明如何處理。此時可以使用責任鏈的形式,用過將各種處理行為設定成為乙個鏈條形式,將請求逐級傳送。如果遇到合適的處理方式就處理該請求,並停止傳輸,如果沒有符合對當前請求進行處理的方式,就繼續想下乙個鏈節點傳送。

舉個栗子:

當前一條汽車零部件傳送帶,在傳送帶的沿線有a、b、c三個汽車組裝點。由於組裝進度不同,同一時刻,不同的組裝點可能需要不同的汽車零部件。零部件隨機的從傳送帶源頭開始傳送,傳送到某一組裝點,如果該組裝點需求該部件,則拿走該部件。如果不需要,則不動該部件,是之繼續往前傳送給下乙個組裝點。假設傳送帶上的零部件總是會被三個組裝點中的乙個取走。

上**:

//虛基類

//h檔案

#pragma once

#include

#include

#include

using namespace std;

class vcomponent

;//cpp檔案

#include "vcomponent.h"

vcomponent::vcomponent(void)

vcomponent::~vcomponent(void)

void vcomponent::setnextcomponent(vcomponent* next)

//具體的類

//h檔案

#pragma once

#include "vcomponent.h"

class acomponent : public vcomponent

;class bcomponent : public vcomponent

;class ccomponent : public vcomponent

;//cpp檔案

#include "specificcomponent.h"

//acomponent

acomponent::acomponent(void)

acomponent::~acomponent(void)

void acomponent::getcomponent(int num)

void acomponent::show()

//bcomponent

bcomponent::bcomponent(void)

bcomponent::~bcomponent(void)

void bcomponent::getcomponent(int num)

void bcomponent::show()

//ccomponent

ccomponent::ccomponent(void)

ccomponent::~ccomponent(void)

void ccomponent::getcomponent(int num)

void ccomponent::show()

//測試

//#include "vld.h"

#include "vcomponent.h"

#include "specificcomponent.h"

vcomponent* inichain();

int main()

vcomponent* inichain()//可以返回區域性指標

設計模式 責任鏈模式

定義 避免請求傳送者與接收者耦合在一起,讓多個物件都有可能接收請求,將這些請求連線成一條鏈,並且沿著這條鏈傳遞請求,直到有物件處理它為止。例項 請假加薪審批 using system using system.collections.generic using system.text namespa...

設計模式 責任鏈模式

責任鏈可以使得系統在不影響客戶端的前提下動態的安排責任鏈和分配責任。責任鏈模式中包含的角色有抽象處理者,具體處理者以及請求的傳送者。責任鏈可以是一條直線,乙個環鏈甚至乙個樹結構。它使得每乙個具體的訊息處理者都有可能處理訊息。抽象的請求處理者 author wly public abstract cl...

設計模式 責任鏈模式

定義 使多個物件都有機會處理請求,從而避免了請求的傳送者和接收者之間的耦合關係。將這些物件連成一條鏈,並沿著這條連傳遞該請求,直到有物件處理它為止。使用場景 多個物件可以處理同一請求,單具體由哪個物件處理則在執行時決定 在請求處理這不明確的情況下向多個物件提交乙個請求 需要動態指定一組物件處理請求 ...