욱'S 노트

Vistor - 데이터 구조를 방문하기 본문

Methdology/Design Pattern

Vistor - 데이터 구조를 방문하기

devsun 2012. 4. 25. 17:21
When Using It

특정한 데이터 구조 가진 오브젝트를 방문하면서 처리를 하고 싶을때

Class Diagram


Sample Code



public interface Element {

public void accept(Visitor visitor);

public void add(Element element);

public List<Element> getChildren();

}


public class ConcreteElement implements Element {

private List<Element> children = new ArrayList<Element>();

@Override

public void accept(Visitor visitor) {

visitor.visitConcreteElement(this);

}


@Override

public void add(Element element) {

children.add(element);

}


@Override

public List<Element> getChildren() {

return this.children;

}

}


public abstract class Visitor {

public abstract void visitConcreteElement(Element element);

}



public class ConcreteVisitor extends Visitor {

@Override

public void visitConcreteElement(Element element) {

List<Element> children = element.getChildren();

for (Element child : children ) {

System.out.println(child);

}

}

}


Caution


특별한 주의사항은 없다.
Comments