This is the first day of my participation in the August Text Challenge.More challenges in August

introduce

The purpose of the visitor pattern is to add a new operation without changing changes to the existing object structure. Imagine that you have a composite object of components whose structure is fixed. We can’t change it, which means we can’t add new elements to the structure. Now, how do we add new functionality to our code without modifying existing classes? The visitor pattern may help us solve this problem.

Take a chestnut

Now, in the middle of an epidemic, let’s say there’s a system that stores our personal information. It is convenient for us to provide the health code, the number of vaccines and the most basic personal information such as mobile phone number and ID card when we travel. There are now two departments, each with different tasks, as follows

  • Hospital (name, ID card, etc…)
  • Access checkpoints (to check vaccinations, etc.)

Use Java code to implement, as follows: define the visitor interface:

public interface Person {
    void accept(Department department);
}
Copy the code

Define red and green code members:

public class RedCodePerson implements Person {
    private String userName;

    private String userPhone;

    private String cardNo;

    private String address;

    @Override
    public void accept(Department department) {
        department.visit(this);
    }

    public RedCodePerson(String userName, String userPhone, String cardNo, String address) {
        this.userName = userName;
        this.userPhone = userPhone;
        this.cardNo = cardNo;
        this.address = address;
    }

    public String getUserName(a) {
        return userName;
    }

    public String getUserPhone(a) {
        return userPhone;
    }

    public String getCardNo(a) {
        return cardNo;
    }

    public String getAddress(a) {
        returnaddress; }}Copy the code

Define green code members:

package com.home.test.visitor.userInfo;

public class GreenCodePerson implements Person{

    private String userName;

    private String userPhone;

    private String cardNo;

    private String address;

    / / the vaccine
    private String vaccine;

    @Override
    public void accept(Department department) {
        department.visit(this);
    }

    public GreenCodePerson(String userName, String userPhone, String cardNo, String address, String vaccine) {
        this.userName = userName;
        this.userPhone = userPhone;
        this.cardNo = cardNo;
        this.address = address;
        this.vaccine = vaccine;
    }

    public String getUserName(a) {
        return userName;
    }

    public String getUserPhone(a) {
        return userPhone;
    }

    public String getCardNo(a) {
        return cardNo;
    }

    public String getAddress(a) {
        return address;
    }

    public String getVaccine(a) {
        returnvaccine; }}Copy the code

Define visitor department interface:

public interface Department {

    void visit(RedCodePerson person);

    void visit(GreenCodePerson person);

}
Copy the code

Define the hospital department access implementation class:

package com.home.test.visitor.userInfo;

public class DocDepartment implements Department {
    @Override
    public void visit(RedCodePerson person) {
        System.out.printf("Red code personnel :% S, mobile phone number :% S, vaccination status :% S, quarantine begins! %n",
                person.getUserName(),
                person.getUserPhone(),
                person.getAddress());
    }

    @Override
    public void visit(GreenCodePerson person) {
        System.out.printf("Green code personnel :% S, mobile number :%s, vaccination status :% S, go home.%n", person.getUserName(), person.getUserPhone(), person.getVaccine()); }}Copy the code

Define the township access implementation class:

package com.home.test.visitor.userInfo;

/** * Town access permission: name, mobile phone number, vaccination status, address, ID number */
public class VillageDepartment implements Department {

    @Override
    public void visit(RedCodePerson person) {
        System.out.printf("Red code personnel :% S, mobile phone number :% S, ID number :% S, address :%s, please check the secret contact personnel in time! %n",
                person.getUserName(),
                person.getUserPhone(),
                person.getCardNo(),
                person.getAddress());
    }

    @Override
    public void visit(GreenCodePerson person) {
        System.out.printf("Green code personnel :%s, mobile phone number :%s, ID number :%s, vaccination status :%s,",
                person.getUserName(),
                person.getUserPhone(),
                person.getCardNo(),
                person.getVaccine());
        if (("Unvaccinated").equals(person.getVaccine())) {
            System.out.println("Please inform the person in time to be vaccinated.");
        } else {
            System.out.println(Please remind me to drink plenty of hot water.); }}}Copy the code

Define test Demo:

package com.home.test.visitor.userInfo;

import java.util.ArrayList;
import java.util.List;

public class ClientDemo {

    public static void main(String[] args) {
        List<Person> personList = new ArrayList<Person>() {{
            add(new GreenCodePerson("Job"."13188880000"."866111"."New Work"."Unvaccinated"));
            add(new GreenCodePerson("Job2"."13188889999"."866112"."New Work"."Unvaccinated"));
            add(new GreenCodePerson("Job3"."13200000000"."866113"."New Work"."Inoculated"));
            add(new RedCodePerson("Li Fugui"."13200000001"."866114"."New Work"));
        }};
        System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the hospital authority view -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
        DocDepartment docDepartment = new DocDepartment();
        personList.forEach(person -> person.accept(docDepartment));
        System.out.println("-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- township department permission check -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --");
        VillageDepartment villageDepartment = newVillageDepartment(); personList.forEach(person -> person.accept(villageDepartment)); }}Copy the code

Output result:

-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- the hospital authority to view -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - green yard personnel: Job, mobile phone number: 13188880000, vaccination: unvaccinated, put home. Green code personnel :Job2, mobile phone number :13188889999, vaccination status: not vaccinated, put back home. Green code personnel :Job3, mobile phone number :13200000000, vaccination status: vaccinated, put back home. Red code: Li Fugui, mobile phone number :13200000001, vaccination status :New Work, start isolation! -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- township department permission check -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - green yard personnel: Job, mobile phone number: 13188880000, id: 866111, vaccination: unvaccinated, please inform the staff vaccination Green code personnel :Job2, mobile phone number :13188889999, ID number :866112, vaccination status: not vaccinated, please inform the personnel in time. Green Code personnel :Job3, mobile phone number :13200000000, ID number :866113, vaccination status: vaccinated, please remind to drink more hot water. Red code personnel: Li Fugui, mobile phone number :13200000001, ID number :866114, address :New Work, please timely check the secret contact personnel!Copy the code

instructions

The visitor pattern is a type of behavior design pattern and is used when we want to perform operations on a group of similar types of objects. With the help of the visitor pattern, we can move the operation logic from an object to another class.

The visitor pattern consists of two parts: a method called Visit(), implemented by the visitor, and an accessible class that provides each element invocation in the data structure to Accept the visitor’s Accept() method

The following UML diagram:

How to learn the visitor pattern

When I first learned the visitor model, I was also very difficult to understand, because I had limited understanding

So what do you do? Knock on some code, find more visitor blogs, and look at the examples above. Don’t copy and paste, or you’ll easily miss details. The details are fine. Just bear with me. In the meantime, don’t be afraid of it. Take a few minutes each day to type in an example of visitor patterns. Then try to write an example and a summary. Finally, look at some conceptual things. That’s why we put the instructions at the end. Many blog concepts are not as good as code.

The concept of eight-part essay

All we need to do is add a function to each element of the structure that accepts the visitor class. Our components will then allow visitors to implement access to them and perform any desired action on the element. Because we won’t change the code, we can still extend the functionality by providing new visitor implementations. For example: In the example above, we could add a logic to handle yellow code without changing the existing class.