What if you could add new features without rewriting your whole code every time?
Why Visitor pattern in LLD? - Purpose & Use Cases
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.
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 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.
class Circle { double area() { ... } void draw() { ... } } class Square { double area() { ... } void draw() { ... } }
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); } }You can add new operations easily without touching existing shape code, making your system flexible and maintainable.
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.
Separates operations from object structures.
Makes adding new operations easy and safe.
Keeps code organized and maintainable.
