Visitor Pattern

wangjh789·2022년 8월 31일
0

Design Pattern

목록 보기
11/13

방문자 패턴은 알고리즘이 작동하는 객체 구조에서 알고리즘을 분리하는 방법

방문자와 방문 공간을 분리해 방문 공간이 방문자를 맞이할 때 이후의 로직은 방문자에게 모두 위임하는 패턴이다.

public interface ShoppingItem {
    double accept(ShoppingCartVisitor visitor);
}
public class Chair implements ShoppingItem {

    private String type;
    private double price;

    public Chair(String type, double price) {
        this.type = type;
        this.price = price;
    }

    public double getPrice() {
        return price;
    }

    @Override
    public double accept(ShoppingCartVisitor visitor) {
        return visitor.visit(this);
    }
}

public class Table implements ShoppingItem {

    private String type;
    private double price;

    public Table(String type, double price) {
        this.type = type;
        this.price = price;
    }

    public double getPrice() {
        return price;
    }

    @Override
    public double accept(ShoppingCartVisitor visitor) {
        return visitor.visit(this);
    }

}

방문공간 ShoppingItem 인터페이스와 구현체

public interface ShoppingCartVisitor {
    double visit(Table table);

    double visit(Chair chair);
}
public class ShoppingCart implements ShoppingCartVisitor {
    @Override
    public double visit(Table table) {
        return table.getPrice();
    }

    @Override
    public double visit(Chair chair) {
        return chair.getPrice();
    }
}

방문자 ShoppingCartVisitor

새로운 방문공간이 생기면 OCP를 위반한다.
새로운 방문자가 생기는 상황엔 코드를 건들 필요가 없어 유리하다.

profile
기록

0개의 댓글