BAEL-1792 overview of visitor design pattern (#4352)

This commit is contained in:
Denis 2018-06-02 06:41:52 +02:00 committed by Grzegorz Piwowarek
parent c99aae6e56
commit 9c26833fa1
7 changed files with 101 additions and 0 deletions

View File

@ -0,0 +1,20 @@
package com.baeldung.visitor;
import java.util.ArrayList;
import java.util.List;
public class Document extends Element {
List<Element> elements = new ArrayList<>();
public Document(String uuid) {
super(uuid);
}
@Override
public void accept(Visitor v) {
for (Element e : this.elements) {
e.accept(v);
}
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.visitor;
public abstract class Element {
public String uuid;
public Element(String uuid) {
this.uuid = uuid;
}
public abstract void accept(Visitor v);
}

View File

@ -0,0 +1,14 @@
package com.baeldung.visitor;
public class ElementVisitor implements Visitor {
@Override
public void visit(XmlElement xe) {
System.out.println("processing xml element with uuid: " + xe.uuid);
}
@Override
public void visit(JsonElement je) {
System.out.println("processing json element with uuid: " + je.uuid);
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.visitor;
public class JsonElement extends Element {
public JsonElement(String uuid) {
super(uuid);
}
public void accept(Visitor v) {
v.visit(this);
}
}

View File

@ -0,0 +1,8 @@
package com.baeldung.visitor;
public interface Visitor {
void visit(XmlElement xe);
void visit(JsonElement je);
}

View File

@ -0,0 +1,23 @@
package com.baeldung.visitor;
import java.util.UUID;
public class VisitorDemo {
public static void main(String[] args) {
Visitor v = new ElementVisitor();
Document d = new Document(generateUuid());
d.elements.add(new JsonElement(generateUuid()));
d.elements.add(new JsonElement(generateUuid()));
d.elements.add(new XmlElement(generateUuid()));
d.accept(v);
}
private static String generateUuid() {
return UUID.randomUUID()
.toString();
}
}

View File

@ -0,0 +1,12 @@
package com.baeldung.visitor;
public class XmlElement extends Element {
public XmlElement(String uuid) {
super(uuid);
}
public void accept(Visitor v) {
v.visit(this);
}
}