The visitor pattern of design pattern 19

background

There are such scenarios in real life. There are many different elements in a collection object, and there are many different visitors and access methods for each element. For example, there are many different commodities in a supermarket, and there are many customers buying clothes. Different customers have different evaluations of different products.

When encountering a data structure with relatively stable data elements that are processed and a variety of access methods, we can use the visitor model. Through the visitor model, we can separate the access method from the data structure, so that we can extend the new access method and achieve flexible expansion without modifying the original program code.

What is the visitor pattern

The above text may be in the cloud. Now you only need to know that the function of using the visitor pattern is to separate the elements in the data structure from the operation methods.

Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates. It is possible to define new operations that act on these elements without changing the data structure.)

The visitor pattern is mainly composed of the following 5 elements:

  • Abstract visitor (Visitor) role: define an interface to access specific elements, for each specific element class corresponds to a visit operation visit (), the parameter type in this operation identifies the specific element to be visited.

  • Specific visitor (ConcreteVisitor) role: implements each access operation declared in the abstract visitor role, and determines what the visitor should do when accessing an element.

  • Abstract element (Element) role: Declare an interface that contains the accept() operation, and the accepted visitor object is used as the parameter of the accept() method.

  • Concrete element (ConcreteElement) role: implements the accept() operation provided by the abstract element role. The method body is usually visitor.visit(this). In addition, the concrete element may also contain operations related to its own business logic.

  • Object Structure Role: It is a container that contains element roles and provides a method for visitors to traverse all elements in the container. It is usually implemented by aggregate classes such as List, Set, and Map.

The structure diagram is as follows:

Visitor mode

Code

Element

public interface Element {
    void accept(Visitor visitor);
}

ConcreteElement

public class ConcreteElementA implements Element {
    @Override
    public void accept(Visitor visitor) {
        visitor.visit(this);
    }

    public String operationA() {
        return "具体元素A的操作。";
    }
}
public class ConcreteElementB implements Element {
    @Override
    public void accept(Visitor visitor) {
        visitor.visit(this);
    }

    public String operationB() {
        return "具体元素B的操作。";
    }
}

Visitor

public interface Visitor {
    void visit(ConcreteElementA element);
    void visit(ConcreteElementB element);
}

ConcreteVisitor

public class ConcreteVisitorA implements Visitor {
    @Override
    public void visit(ConcreteElementA element) {
        System.out.println("具体访问者A访问-->" + element.operationA());
    }

    @Override
    public void visit(ConcreteElementB element) {
        System.out.println("具体访问者A访问-->" + element.operationB());
    }
}
public class ConcreteVisitorB implements Visitor {
    @Override
    public void visit(ConcreteElementA element) {
        System.out.println("具体访问者B访问-->" + element.operationA());
    }

    @Override
    public void visit(ConcreteElementB element) {
        System.out.println("具体访问者B访问-->" + element.operationB());
    }
}

ObjectStructure

public class ObjectStructure {
    private List<Element> list = new ArrayList<>();

    public void accept(Visitor visitor) {
        Iterator<Element> i = list.iterator();
        while (i.hasNext()) {
            i.next().accept(visitor);
        }
    }

    public void add(Element element) {
        list.add(element);
    }

    public void remove(Element element) {
        list.remove(element);
    }
}

Test code

@Test
public void test() {
    ObjectStructure os=new ObjectStructure();
    os.add(new ConcreteElementA());
    os.add(new ConcreteElementB());
    Visitor visitor=new ConcreteVisitorA();
    os.accept(visitor);
    System.out.println("------------------------");
    visitor=new ConcreteVisitorB();
    os.accept(visitor);
}

Test Results:

具体访问者A访问-->具体元素A的操作。
具体访问者A访问-->具体元素B的操作。
------------------------
具体访问者B访问-->具体元素A的操作。
具体访问者B访问-->具体元素B的操作。

The call chain is as follows:

//举例A:
ObjectStructure#accept() -> ConcreteElementA#accept() -> ConcreteVisitorA#visit()

Thinking about the visitor pattern

So when do we use visitor mode?

When the structure of the object is stable, but the operation algorithm often changes, we can use the visitor mode to avoid the change of these operation algorithms to affect the data structure. We separate the algorithm from the data structure.

In fact, when we use iterators to traverse the collection elements, in addition to using the iterator mode, we also use the visitor mode. The collection itself does not participate in the traversal, but is obtained through the iterator method.

In this kind of place you must consider using the visitor pattern: business rules require multiple different objects to be traversed. This itself is also the starting point of the visitor pattern. The iterator pattern can only access data of the same type or the same interface (of course, if you use instanceof, you can access all the data, there is no argument), and the visitor pattern is the iterator pattern The expansion of, you can traverse different objects, and then perform different operations, that is, perform different operations for different objects to be accessed.

The visitor mode is a centralized and regular mode, especially suitable for large-scale reconstruction projects. At this stage, the requirements are very clear, and the function points of the original system are also clear. Some functions can be easily sorted out through the visitor mode. , To achieve the ultimate goal-function centralization, such as a unified report calculation, UI display, etc., we can also mix with other modes to build our own set of filters or interceptors.

 

Recommended in the past

Scan the QR code to get more exciting. Or search Lvshen_9 on WeChat , you can reply to get information in the background

  1. 回复"java" 获取java电子书;

  2. 回复"python"获取python电子书;

  3. 回复"算法"获取算法电子书;

  4. 回复"大数据"获取大数据电子书;

  5. 回复"spring"获取SpringBoot的学习视频。

  6. 回复"面试"获取一线大厂面试资料

  7. 回复"进阶之路"获取Java进阶之路的思维导图

  8. 回复"手册"获取阿里巴巴Java开发手册(嵩山终极版)

  9. 回复"总结"获取Java后端面试经验总结PDF版

  10. 回复"Redis"获取Redis命令手册,和Redis专项面试习题(PDF)

  11. 回复"并发导图"获取Java并发编程思维导图(xmind终极版)

Another: Click [ My Benefits ] to have more surprises.

Guess you like

Origin blog.csdn.net/wujialv/article/details/109713535