concept

Encapsulate operations that operate on object elements in a stable object structure without changing the object structure. For example, an object structure consists of many objects, each of which has an Accept method that accepts visitor objects. A visitor is an interface that has a visit method. The Accept method is applied to each element as it traverses the object structure, which in turn calls the visit method in the visit (for handling different object elements)

advantages

Good scalability, decoupling data structure and operational structure

disadvantages

It violates the principle of dependency inversion, and the modification cost is high when specific elements are changed.

implementation

  • Visitor – Visitor interface or abstract class that defines access behavior for each element and theoretically has the same number of methods as the number of elements (each element should have one visit(ElementX e)) (that is, process different elements through method overloading)
  • ConcreteVisitor – ConcreteVisitor
  • Element — An Element interface or abstract class that defines the Accept method
  • ElementA, ElementB — Concrete element class
  • ObjectStructure — ObjectStructure. The collection of elements is managed internally and can be iterated to the Visitor for access.
/* element class */ public class Staff {public String name; public int kpi; public abstract void accept(Visitor visitor); } public class Engineer extends Staff { @Override public void accept (Visitor visitor){ visitor.visit(this); } public intgetkpi() {return 1500;
    }
}
public class Manager extends Staff {

    @Override
    public void accept (Visitor visitor){
        visitor.visit(this);
    }

    public int getproductandkpi() {returnPublic class BusinessReport{List<Staff> l = new LinkedList(); publicBusinessReport(){/* Initialize list l.dd (new Manager()"Manager Wang")); . */ } public void showResult(Visitor visitor){for(Staff s : l){ s.accept(visitor); }} /* Visitor */ public interface Visitor {public void visit(Engineer e); public void visit(Manager e); } // Visitor 1 public implements Visitor {@override public void visit(Engineer e){ System.out.println(e.kpi); } @override public void visit(Manager e){system.out.println (e.kpi + "OK"); }} // Visitor 2... You can define different actions for different visitorsCopy the code