职责链模式允许你将请求沿着处理者链进行发送。收到请求后,每个处理者均可对请求进行处理,或将其传递给链上的下个处理者。
职责链模式:避免将一个请求的发送者和接收者耦合在一起,让多个对象都有机会处理请求。将接收请求的对象连接成一条链,并且沿着这条链传送请求,直到有一个对象能够处理它为止。
实现方式:
#include <iostream>
#include <string>
#include <vector>
class Handler {
public:
virtual ~Handler() {}
virtual Handler *setNext(Handler *handler) = 0;
virtual std::string Handle(std::string request) = 0;
};
class AbstractHandler : public Handler {
private:
Handler *next_handler_;
public:
AbstractHandler() : next_handler_(nullptr) {}
Handler *setNext(Handler *handler) override {
this->next_handler_ = handler;
return handler;
}
std::string Handle(std::string request) override {
if( this->next_handler_ ) {
return this->next_handler_->Handle(request);
}
return {};
}
};
class ConcreteHandlerA: public AbstractHandler {
public:
std::string Handle(std::string request) override {
if(request == "A") {
return "A: 我 能 处 理 它 " + request + ".\n";
} else {
return AbstractHandler::Handle(request);
}
}
};
class ConcreteHandlerB: public AbstractHandler {
public:
std::string Handle(std::string request) override {
if(request == "B") {
return "B: 我 能 处 理 它 " + request + ".\n";
} else {
return AbstractHandler::Handle(request);
}
}
};
class ConcreteHandlerC: public AbstractHandler {
public:
std::string Handle(std::string request) override {
if(request == "C") {
return "C: 我 能 处 理 它 " + request + ".\n";
} else {
return AbstractHandler::Handle(request);
}
}
};
void ClientCode(Handler &handler) {
std::vector<std::string> request = {"B", "A", "D"};
for(const std::string &r: request) {
std::cout << "Client: 谁 能 处 理 " << r << " ?\n";
const std::string result = handler.Handle(r);
if(!result.empty()) {
std::cout << " " << result;
} else {
std::cout << " " << r << ": 不 能 被 处 理!\n";
}
}
}
int main(int argc, char *argv[]) {
ConcreteHandlerA *a = new ConcreteHandlerA;
ConcreteHandlerB *b = new ConcreteHandlerB;
ConcreteHandlerC *c = new ConcreteHandlerC;
a->setNext(b)->setNext(c);
std::cout << "Chain: A > B > C\n";
ClientCode(*a);
std::cout << "\n";
std::cout << "Chain: B > C\n";
ClientCode(*b);
delete a;
delete b;
delete c;
return 0;
}
# -*- coding: utf-8 -*-
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Any, Optional
class Handler(ABC):
"""
"""
@abstractmethod
def set_next(self, handler: Handler) -> Handler:
pass
@abstractmethod
def handle(self, request) -> Optional[str]:
pass
class AbstractHandler(Handler):
"""
"""
_next_handler: Handler = None
def set_next(self, handler: Handler) -> Handler:
self._next_handler = handler
return handler
@abstractmethod
def handle(self, request: Any) -> str:
if self._next_handler:
return self._next_handler.handle(request)
return None
class ConcreteHandlerA(AbstractHandler):
"""
"""
def handle(self, request: Any) -> str:
if request == "A":
return f"A: 我 能 处 理 它 {request}"
else:
return super().handle(request)
class ConcreteHandlerB(AbstractHandler):
"""
"""
def handle(self, request: Any) -> str:
if request == "B":
return f"B: 我 能 处 理 它 {request}"
else:
return super().handle(request)
class ConcreteHandlerC(AbstractHandler):
"""
"""
def handle(self, request: Any) -> str:
if request == "C":
return f"C: 我 能 处 理 它 {request}"
else:
return super().handle(request)
def client_code(handler: Handler) -> None:
for r in ["B", "A", "D"]:
print(f"Client: 谁 能 处 理 {r} ?")
result = handler.handle(r)
if result:
print(f" {result}")
else:
print(f" {r} 不 能 被 处 理.")
if __name__ == "__main__":
a = ConcreteHandlerA()
b = ConcreteHandlerB()
c = ConcreteHandlerC()
a.set_next(b).set_next(c)
print("Chain: A > B > C")
client_code(a)
print("\n")
print("Subchain: B > C")
client_code(b)
同上。
同上。
原文:https://www.cnblogs.com/parzulpan/p/13561076.html