ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 방문자(비지터) 패턴
    디자인 패턴 2010. 11. 17. 17:26

    (데이터 구조 내의) 객체 타입별로 달리 적용되어야 하는 오퍼레이션을 (순회하는) 방문자 객체에 정의

    type separation from visitor object to make change modular without editing and recompiling existing classes


    처리되어야 하는 요소에 대한 클래스를 변경하지 않고 새로운 오퍼레이션을 정의

    각 클래스로부터 관련된 오퍼레이션을 모아 visitor라는 별도의 클래스로 만들고 이를 전달하여 순환

    구조를 수정하지 않고도 실질적으로 새로운 동작을 기존의 객체 구조에 추가할 수 있게 된다


    "컨테이너에 포함되어 있는 객체의 구조(accessor)는 고정적인데 그 객체(의 구조)에 적용되어야 하는 오퍼레이션은 정해져 있지 않으므로, 그 객체에 둘 수 없다"



    declare interface Visitor;

    interface Element {
        public void accept(Visitor vObj);
    }

    interface Visitor {
        public void visit(Element eObj);
    }

    class HexReportVisitor implements Visitor {
        public void visit(Element eObj) {
            int i = eObj.getIntValue();
        }
    }

    class ConcreteElementA implements Element {
        public void accept(Visitor vObj) {
            vObj.visit(this);
        }

    }
    /*

    interface Visitor {
        public void visit(ConcreteElementA aObj);
        public void visit(ConcreteElementB bObj);
        ...
    }


    class HexReportVisitor implements Visitor {
        public void visit(ConcreteElementA aObj) {
            int i = aObj.getIntValue();

        }

        public void visit(ConcreteElementB bObj) {
            String s = bObj.getValue();

        }
    }

    */
    List<Element> container = new List<Element>();

    container.add(new ConcreteElementA( ... ));
    container.add(new ConcreteElementB( ... ));

    HexReportVisitor hexReporter = new HexReportVisitor();
    TextReportVisitor textReporter = new TextReportVisitor();

    for( Element e: container )
        e.accept( hexReporter );

    for( Element e: container )
        e.accept( textReporter );


    참조 사이트:



Designed by Tistory.