Backend/디자인패턴
방문자 패턴
chjysm
2023. 5. 31. 16:24
방문자 패턴?
공통된 객체의 데이터 구조와 처리 알고리즘을 분리하는 패턴이다.
예를 들어 a,b,c 객체에 동일한 데이터 처리 알고리즘을 적용해야 하는데
개방/폐쇄 원칙을 지키기 위해 기존 객체에 알고리즘 로직을 중복으로 추가하는 것 대신,
방문자 패턴을 적용하면 된다.
방문자 패턴의 구조
- Element : 요소는 방문자 를 수락하는 인터페이스 이다.
- ConcreteElement : 구상 요소는 요소에서 선언한 수락 메서드를 구현한 구현체 이다. 호출을 적절한 방문자 메서드로 리다이렉트 한다.
- Visitor : 방문자는 구상요소들을 인수로 사용 할 수 있는 방문자 메서드들의 집합을 선언한다.
- ConcreteVisitor : 비지터 인터페이스의 구현체 각 구상 요소 클래스들에 맞춤으로 제작된 방문자 메서드를 구현한다.
방문자 패턴의 장점
- 개방/폐쇄 원칙
- 단일 책임 원칙
방문자 패턴의 단점
- Element 가 추가될 때 마다 모든 Visitor를 업데이트 해야한다.
- Visitor가 Element 의 비공개 필드에 접근하기 위한 권한이 없을 수 있다.
방문자 패턴의 구현
public interface Visitor {
void visit(ConcreteElementA a);
void visit(ConcreteElementB b);
}
public class ConcreteVisitor implements Visitor{
@Override
public void visit(ConcreteElementA a) {
System.out.println(a.getA1());
System.out.println(a.getA2());
System.out.println(a.getA3());
}
@Override
public void visit(ConcreteElementB b) {
System.out.println(b.getB1());
System.out.println(b.getB2());
System.out.println(b.getB3());
System.out.println(b.getB4());
}
}
public interface Element {
void accept(Visitor visitor);
}
@Getter
@Setter
public class ConcreteElementA implements Element{
private String a1;
private String a2;
private String a3;
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
@Getter
@Setter
public class ConcreteElementB implements Element{
private String b1;
private String b2;
private String b3;
private String b4;
@Override
public void accept(Visitor visitor) {
visitor.visit(this);
}
}
언제 사용해야 할까?
- 복잡한 객체 구조의 모든 요소에 동일 작업을 추가해야 할 때
- 보조 행동들의 비즈니스 로직을 정리하고 싶을 때
- 행동이 계층 구조의 일부 클래스 들에게만 의미가 있을 때
참조