[Design Pattern in C++] Chain of Responsibility

Heron Yang
Heron’s Blog 海龍的部落格
1 min readNov 28, 2020

--

Design Pattern in C++ is a series of Heron’s blog posts that shares C++ code examples of each design pattern. You can find all code at this Github repo. I don’t explain the details of each pattern in these posts, please refer to other resources if that’s what you’re looking for.

Definition

Chain of Responsibility pattern passes a request into a chain of objects — each object processes the request and decides whether to pass to the next object.

Code

Logger is an abstract class implemented by ConsoleLogger, FileLogger, and EmailLogger. Logger provides AddNext() to chain another Logger. When the caller calls Log(), the logger writes log and asks the next logger does the same if needed.

logger.h

logger.cc

console_logger.h

console_logger.cc

Note that FileLogger and EmailLogger are similar to ConsoleLogger so I skipped them in this post.

main.cc

Full Code

--

--