Skip to content
LLD Learn/Behavioral Patterns
Browsing as a guest. Sign in to save your progress and earn XP as you complete chapters.

Chain of Responsibility & Template Method

3 min read

You'll learn to

  • -Explain Chain of Responsibility as a line of handlers, each of which may act, stop the request or pass it on
  • -Explain Template Method as a recipe whose order is fixed while individual steps vary
  • -Tell them apart: Chain decides at run time which handlers act, Template fixes which steps run

Both patterns organize a multi-step process, from opposite directions. Chain of Responsibility sends a request along a line of handlers, and each one decides whether to act. Template Method fixes the order of the steps in one place and lets subclasses fill in the individual steps.

Chain of Responsibility: A Line of Independent Handlers

Think of airport security. You pass the ID check, then the bag scanner, then the metal detector. Each checkpoint can stop you, or wave you on to the next. Nobody at the front desk knows how many checkpoints there are. Web servers work like this too, where the checkpoints are called middleware. Each handler either handles the request, passes it to the next handler, or does both.

The demo builds a three-step chain: check the sign-in, check the request limit, write a log entry. The first request has no credentials, so the first handler stops it. The second passes all three.

Press Run: request 1 stops at the first handler, request 2 flows through all three

Adding a new concern, such as compression, means inserting one handler into the chain. None of the other handlers change.

Template Method: One Fixed Recipe, Customizable Steps

Template Method is a recipe card. The order of the steps is printed on the card and never changes: prepare, cook, serve. What you cook at each step differs between recipes. In code, a base-class method (the template) fixes the order of the steps, and subclasses supply the details of individual steps. A data pipeline that always reads, transforms and writes, but reads from different formats, is a natural fit.

Press Run: the same read-transform-write order, different details at each step

The distinction interviewers like: Chain of Responsibility is about which handlers run, decided one by one at run time. Template Method is about which steps run, fixed by the base class, with only the content of each step varying.

Interview Signal is part of Pro

See a real weak answer next to a real strong one for this exact topic.

Quiz is part of Pro

Test what you just read with a short quiz, and bank the XP.

Discussion0

Join the Discussion

Sign in to leave comments, reply to others, or like insights.

Sign In to ScaleDojo

No comments yet. Be the first to start the thread!