日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

大话设计模式--职责连模式 Chain of Resposibility -- C++实现实例

發布時間:2025/3/15 c/c++ 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 大话设计模式--职责连模式 Chain of Resposibility -- C++实现实例 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1. 職責鏈模式: 使多個對象都有機會處理請求,從而避免請求發送者和接受者之間的耦合關系,將這個對象連成一條鏈,并沿著這條鏈傳遞該請求,直到有一個對象處理它。

當客戶提交一個請求時,請求是沿著鏈傳遞直到有一個ConcreteHandler對象負責處理它,接收者和發送者都沒有對方的明確信息,且鏈中的對象并不知道鏈的結構。

結果是職責鏈可以簡化對象的互相連接,他們僅需一個指向其后繼者的引用,而不需要保持它所有后繼者的引用。

一個請求極有可能到了鏈的最末端還是得不到處理,或者沒有正確配置而得不到處理,需要事先考慮全面。

?

實例:

handler.h handler.cpp

#ifndef HANDLER_H #define HANDLER_Hclass Handler { public:Handler();~Handler();void setSuccessor(Handler *successor);void virtual handlerRequest(int request)=0;protected:Handler *successor; };#endif // HANDLER_H #include "handler.h"Handler::Handler() { successor = 0; }Handler::~Handler() {delete successor; }void Handler::setSuccessor(Handler *successor) {this->successor = successor; }


concretehandler1.h concretehandler1.cpp

#ifndef CONCRETEHANDLER1_H #define CONCRETEHANDLER1_H#include "handler.h"class ConcreteHandler1 : public Handler { public:ConcreteHandler1();void handlerRequest(int request); };#endif // CONCRETEHANDLER1_H #include "concretehandler1.h" #include <stdio.h>ConcreteHandler1::ConcreteHandler1() { }void ConcreteHandler1::handlerRequest(int request) {if( request >=0 && request < 10 ){printf("ConcreteHandler1 handlerRequest\n");}else{if( successor!=0 ){printf("the next one handler\n");successor->handlerRequest(request);}} }


concretehandler2.h concretehandler2.cpp

#ifndef CONCRETEHANDLER2_H #define CONCRETEHANDLER2_H#include "handler.h"class ConcreteHandler2 : public Handler { public:ConcreteHandler2();void handlerRequest(int request); };#endif // CONCRETEHANDLER2_H #include "concretehandler2.h" #include <stdio.h>ConcreteHandler2::ConcreteHandler2() { }void ConcreteHandler2::handlerRequest(int request) {if( request >=10 && request < 20 ){printf("ConcreteHandler2 handlerRequest\n");}else{if( successor!=0 ){printf("the next one handler\n");successor->handlerRequest(request);}} }


main.cpp

#include <iostream> #include "concretehandler1.h" #include "concretehandler2.h" using namespace std;int main() {cout << "Chain_of_responsibility test!" << endl;Handler *h1 = new ConcreteHandler1();Handler *h2 = new ConcreteHandler2();h1->setSuccessor(h2);h1->handlerRequest(15);return 0; }



?

?

?

?

轉載于:https://www.cnblogs.com/xj626852095/p/3648179.html

總結

以上是生活随笔為你收集整理的大话设计模式--职责连模式 Chain of Resposibility -- C++实现实例的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。