Bird
0
0
LLDsystem_design~3 mins

Why Visitor pattern in LLD? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could add new features without rewriting your whole code every time?

The Scenario

Imagine you have a collection of different shapes like circles, squares, and triangles. You want to perform various operations on them, such as calculating area, drawing, or exporting data. Doing this manually means writing separate code for each shape and each operation, mixing all logic together.

The Problem

This manual approach quickly becomes messy and hard to maintain. Every time you add a new operation, you must change all shape classes. This leads to duplicated code, errors, and lots of time spent updating multiple places.

The Solution

The Visitor pattern lets you separate operations from the objects they work on. You create visitor classes for each operation and let shapes accept visitors. This way, you add new operations without changing shape classes, keeping code clean and easy to extend.

Before vs After
Before
class Circle { double area() { ... } void draw() { ... } }
class Square { double area() { ... } void draw() { ... } }
After
interface Visitor { void visitCircle(Circle c); void visitSquare(Square s); }
class AreaVisitor implements Visitor { ... }
class DrawVisitor implements Visitor { ... }
class Circle { void accept(Visitor v) { v.visitCircle(this); } }
class Square { void accept(Visitor v) { v.visitSquare(this); } }
What It Enables

You can add new operations easily without touching existing shape code, making your system flexible and maintainable.

Real Life Example

In a graphic editor, you can add new features like exporting shapes to different formats or applying filters by just creating new visitors, without changing the shape classes.

Key Takeaways

Separates operations from object structures.

Makes adding new operations easy and safe.

Keeps code organized and maintainable.