HomeAboutMeBlogGuest
© 2025 Sejin Cha. All rights reserved.
Built with Next.js, deployed on Vercel
📝
남득윤 학습 저장소
/
객체 지향 프로그래밍
객체 지향 프로그래밍
/
디자인 패턴
디자인 패턴
/
Visitor Pattern
Visitor Pattern
Visitor Pattern

Visitor Pattern

💡
객체에서 처리 분리하기!

Motivation

콜렉션에 포함된 객체의 정확한 타입을 모른 상태로 메소드를 호출해야하는 경우가 있습니다.
가장 간단한 해결 방식은 if과 instanceof로 이루어진 분기문을 떡칠하는 것이지만 이것은 OCP를 위배하고 전혀 객체지향 스럽지 않습니다.
 
이때 Visitor 패턴을 적용할 수 있습니다.

Intent

Visitor is a behavioral design pattern that lets you separate algorithms from the objects on which they operate.
 

Implementation

notion image
 
💡
로직은 ConcreteVisitorN의 visit 메서드 ConcreteElementN의 accept메서드에 모두 적용될 수 있다.
방문하는 Element의 타입에 따라 다른 로직을 제공

Applicablity

  • 복잡한 객체구조를 가진 콜렉션의 원소에 operation을 적용하고 싶을때
  • 비즈니스 로직을 보조 로직과 분리하고 싶을 때
  • 클라스 계층의 전체가 아닌 일부분에만 적용가능한 로직이 있는 경우
 

Code Example @ My GitHub

 

Relations with Other Patterns

  • Visitor 패턴은 Command 패턴의 Powerful Version이다.
  • Visitor 패턴을 Composite 패턴으로 구성된 Tree 구조에 적용할 수 있다.
  • Visitor 패턴을 적용할때 Iterator를 활용할 수 있다.