Visitor mode

Posted by neave on Tue, 02 Nov 2021 19:53:51 +0100

brief introduction

Digression: This is the last of the 23 design modes to be written. When I haven't finished writing, I always want to write quickly. Now I'm about to finish writing. I feel that time flies. It took three months to write this series, but I chewed down this hard bone, which is worth recording.

Visitor mode, known as the most complex design mode, is generally unavailable. When I first came into contact, I really couldn't understand why I designed it like this (back and forth dolls). I felt it was encapsulated for packaging. Now let's take a look at how this visitor mode sets dolls.

text

  Sample demo

import random

class Interviewee:
    def __init__(self, name) -> None:
        self.name = name
        self.academic_record  = random.randrange(0,100)      # Academic achievement
        self.technical_proficiency = random.randrange(0,100) # Technical proficiency


    def accept(self, visitor):
        pass


class Student(Interviewee):

    def accept(self, visitor):
        visitor.visit(self)

    def get_academic_record(self):
        return self.academic_record


class SocialMan(Interviewee):

    def accept(self, visitor):
        visitor.visit(self)

    def get_technical_proficiency(self):
        return self.technical_proficiency


class Visitor:
    def __init__(self) -> None:
        pass

    def visit(self, interviewee) -> None:
        pass

class OnCampusRecruitment(Visitor):

    def visit(self, interviewee) -> None:
        print("School recruitment platform")
        if isinstance(interviewee, Student): 
            print("Interviewers{}He is a student. His academic achievements are:{}".format(interviewee.name,interviewee.get_academic_record()))
        elif isinstance(interviewee, SocialMan):
            print("{}Sir, your resume is wrong. Please move to the social recruitment platform".format(interviewee.name))
        else:
            print("Who are you?")

        
class SocialRecruitment(Visitor):

    def visit(self, interviewee) -> None:
        print("Social recruitment platform")
        if isinstance(interviewee, Student): 
            print("{}Classmate, your resume is wrong. Please move to the school recruitment platform".format(interviewee.name))
        elif isinstance(interviewee, SocialMan):
            print("Interviewers{}As a social person, his technical proficiency is:{}%".format(interviewee.name,interviewee.get_technical_proficiency()))
        else:
            print("Who are you?")


class InterviewList:

    def __init__(self) -> None:
        self.interview_list = []

    def add_interview(self,interviewee):
        self.interview_list.append(interviewee)

    def display(self, visitor):
        for interviewee in self.interview_list:
            interviewee.accept(visitor)

i = InterviewList()
i.add_interview(SocialMan("Li Si"))
i.add_interview(Student("Xiao Ming"))
i.add_interview(Student("Xiao Hong"))
i.add_interview(Student("Xiao Fang"))
i.add_interview(SocialMan("Wang Wu"))
i.add_interview(Student("Xiaolan"))
i.add_interview(SocialMan("Zhang San"))

i.display(SocialRecruitment())
i.display(OnCampusRecruitment())

Sample resolution:

In the example, we have a candidate base class. The candidate base class has two subclasses, one is a student and the other is a social person. Each candidate has his own academic achievements and skill proficiency.  

There is a basic class of interview platform. The basic class of interview platform also has two subclasses, one is school recruitment platform and the other is social recruitment platform. Each interview platform focuses on different points. The school recruitment platform only focuses on students' academic achievements, and the social recruitment platform only focuses on the skill proficiency of social people.

Now we have a candidate center, which collects candidate information and puts candidate information on different interview platforms.

The interview process is as follows:

Candidates submit resumes to the application center. The application center puts all candidates on the designated interview platform. Candidates accept(self,visitor) and pass their data to the interview platform for viewing (visit(self)). After receiving the candidate's information, the interview platform accesses the corresponding attributes according to its own needs and gives feedback.

There are two key points in the above process:

  1. Candidates accept(self,visitor) on the interview platform
  2. The interviewer accepts the applicant's information visit(self)

 

summary

Advantages of visitor mode:

  1. It is convenient to switch visitors. You only need to specify different visitors each time

Disadvantages of visitor mode:

  1. Adding new interviewees is troublesome, and it may be necessary to change the access method set by the visitors
  2. Modifying the respondent's attributes and methods will have an impact on visitors, leading to the modification of all visitor methods

  Here is a short summary from Baidu: One visitor pattern is enough - a short book

  • Advantages of visitor mode.

    1. The roles and responsibilities are separated and conform to the principle of single responsibility
      It can be seen from the UML class diagram and the above examples that Visitor, ConcreteVisitor, Element and ObjectStructure have a single responsibility and each takes its own responsibility.
    2. Excellent scalability
      If you need to add new visitors, you can quickly expand by adding the implementation class ConcreteVisitor.
    3. The data structure is decoupled from the operation on the structure, so that the operation set can be changed independently
      Employee attributes (data structures) are decoupled from CEO and CTO visitors (data operations).
    4. flexibility
  • Disadvantages of visitor mode.

    1. The specific elements publish details to visitors, which violates the Dimitri principle
      CEO and CTO need to call the methods of specific employees.
    2. When the specific element is changed, the modification cost is high
      When changing employee attributes, multiple visitors must modify them.
    3. It violates the dependency inversion principle and relies on specific classes in order to achieve "differential treatment", without abstraction
      The visitor visit method relies on the specific methods of specific employees.

Topics: Python OOP