主要将数据结构与数据操作分离。
被访问者中调用访问者访问方法,即告知访问者内部具体细节
public class Visitor_Main {
public static void main(String[] args) {
Element element1 = Demo1_Element.builder().age("age...10").name("name...Demo1_Element").build();
Element element2 = Demo2_Element.builder().weigh("weigh...10").heigh("heigh...Demo2_Element").build();
ElementList elementList = new ElementList();
elementList.add(element1);
elementList.add(element2);
elementList.accept(new Demo_Visit());
}
}
abstract class Visit {
abstract void visit(Demo1_Element element);
abstract void visit(Demo2_Element element);
}
class Demo_Visit extends Visit{
@Override
void visit(Demo1_Element element) {
System.out.println(element.getAge()+"__"+element.getName());
}
@Override
void visit(Demo2_Element element) {
System.out.println(element.getHeigh()+"__"+element.getWeigh());
}
}
interface Element{
//接待访问者
void accept(Visit visit);
}
//对象结构用于存放元素对象,提供内部元素的便利访问方法
class ElementList{
private List<Element> elements = new ArrayList<>();
public boolean add(Element element){
if (element != null)
return elements.add(element);
return Boolean.FALSE;
}
public void accept(Visit visit){
if (CollectionUtils.isEmpty(elements))
return;
elements.forEach(e->e.accept(visit));
}
}
@Data
@Builder
class Demo1_Element implements Element{
private String name;
private String age;
//告知访问者内部细节,接受访问者的访问
@Override
public void accept(Visit visit) {
visit.visit(this);
}
}
@Data
@Builder
class Demo2_Element implements Element{
private String heigh;
private String weigh;
@Override
public void accept(Visit visit) {
visit.visit(this);
}
}