使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这个对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理它为止。
这里发出请求的客户端并不知道哪一个对象会最终处理这个请求,这样系统的更改可以在不影响客户端的情况下动态地重新组织和分配责任。
当客户提交一个请求时,请求是沿着链传递直到一个 ConcreteHandler 对象负责处理它。这样就使得接收者和发送者双方都没有对方的明确消息。
HINT:注意有可能一个请求到链尾都得不到处理。
#include <iostream>
#include <memory>
#include <vector>
class Handler {
public:
void setHandle(const std::shared_ptr<Handler> &handle) { handle_ = handle; }
virtual void handleRequest(int request) = 0;
virtual ~Handler() = default;
protected:
std::shared_ptr<Handler> handle_;
};
class ConcreteHandler1 final : public Handler {
public:
void handleRequest(int request) override {
if (request >= 0 && request <= 10) {
std::cout << "ConcreteHandler1 handle request: " << request << '\n';
} else if (handle_ != nullptr) {
handle_->handleRequest(request);
}
}
virtual ~ConcreteHandler1() = default;
};
class ConcreteHandler2 final : public Handler {
public:
void handleRequest(int request) override {
if (request >= 10 && request <= 20) {
std::cout << "ConcreteHandler2 handle request: " << request << '\n';
} else if (handle_ != nullptr) {
handle_->handleRequest(request);
}
}
virtual ~ConcreteHandler2() = default;
};
class ConcreteHandler3 final : public Handler {
public:
void handleRequest(int request) override {
if (request >= 20 && request <= 30) {
std::cout << "ConcreteHandler3 handle request: " << request << '\n';
} else if (handle_ != nullptr) {
handle_->handleRequest(request);
}
}
virtual ~ConcreteHandler3() = default;
};
auto main() -> int {
std::shared_ptr<Handler> p1 = std::make_shared<ConcreteHandler1>();
std::shared_ptr<Handler> p2 = std::make_shared<ConcreteHandler2>();
std::shared_ptr<Handler> p3 = std::make_shared<ConcreteHandler3>();
p1->setHandle(p2);
p2->setHandle(p3);
std::vector<int> vec = {2, 5, 14, 22, 18, 3, 27, 20};
for (auto i : vec) {
p1->handleRequest(i);
}
return 0;
}