File tree Expand file tree Collapse file tree
patterns/design-patterns/src/main/java/com/baeldung/visitor Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package com .baeldung .visitor ;
2+
3+ import java .util .ArrayList ;
4+ import java .util .List ;
5+
6+ public class Document extends Element {
7+
8+ List <Element > elements = new ArrayList <>();
9+
10+ public Document (String uuid ) {
11+ super (uuid );
12+ }
13+
14+ @ Override
15+ public void accept (Visitor v ) {
16+ for (Element e : this .elements ) {
17+ e .accept (v );
18+ }
19+ }
20+ }
Original file line number Diff line number Diff line change 1+ package com .baeldung .visitor ;
2+
3+ public abstract class Element {
4+
5+ public String uuid ;
6+
7+ public Element (String uuid ) {
8+ this .uuid = uuid ;
9+ }
10+
11+ public abstract void accept (Visitor v );
12+ }
Original file line number Diff line number Diff line change 1+ package com .baeldung .visitor ;
2+
3+ public class ElementVisitor implements Visitor {
4+
5+ @ Override
6+ public void visit (XmlElement xe ) {
7+ System .out .println ("processing xml element with uuid: " + xe .uuid );
8+ }
9+
10+ @ Override
11+ public void visit (JsonElement je ) {
12+ System .out .println ("processing json element with uuid: " + je .uuid );
13+ }
14+ }
Original file line number Diff line number Diff line change 1+ package com .baeldung .visitor ;
2+
3+ public class JsonElement extends Element {
4+
5+ public JsonElement (String uuid ) {
6+ super (uuid );
7+ }
8+
9+ public void accept (Visitor v ) {
10+ v .visit (this );
11+ }
12+ }
Original file line number Diff line number Diff line change 1+ package com .baeldung .visitor ;
2+
3+ public interface Visitor {
4+
5+ void visit (XmlElement xe );
6+
7+ void visit (JsonElement je );
8+ }
Original file line number Diff line number Diff line change 1+ package com .baeldung .visitor ;
2+
3+ import java .util .UUID ;
4+
5+ public class VisitorDemo {
6+
7+ public static void main (String [] args ) {
8+
9+ Visitor v = new ElementVisitor ();
10+
11+ Document d = new Document (generateUuid ());
12+ d .elements .add (new JsonElement (generateUuid ()));
13+ d .elements .add (new JsonElement (generateUuid ()));
14+ d .elements .add (new XmlElement (generateUuid ()));
15+
16+ d .accept (v );
17+ }
18+
19+ private static String generateUuid () {
20+ return UUID .randomUUID ()
21+ .toString ();
22+ }
23+ }
Original file line number Diff line number Diff line change 1+ package com .baeldung .visitor ;
2+
3+ public class XmlElement extends Element {
4+
5+ public XmlElement (String uuid ) {
6+ super (uuid );
7+ }
8+
9+ public void accept (Visitor v ) {
10+ v .visit (this );
11+ }
12+ }
You can’t perform that action at this time.
0 commit comments