The visitor pattern of java designer pattern (14)

The visitor pattern of java designer pattern①④

The real life is to take care of your daily tasks. Don't ask for love and prospects that have nothing to do with you. Do not dwell on unnecessary emotions and judgments. Do not delusion, not indulge yourself in it. Don’t hurt yourself or be hostile to others. Do not perform and do not believe in other people's performances.

Design pattern learning, I will blog about 23 design patterns in the near future , so stay tuned~
—2021/1/17

definition

Represents an operation that acts on each element in an object structure. It allows you to define new operations that act on these elements without changing the class of each element.

Baidu Encyclopedia

Application scenario

Assuming that the final exam results are to be announced:

The scores are divided into: Chinese mathematics
students are divided into: Xiao Ming, Xiao Hong

If you add a subject or add a student in the traditional way, you have to change the original code, which violates the open and closed principle (open for extension and closed for modification), here is the visitor mode

UML类图(1.1):

Insert picture description here

  • Red box: interviewee (score)

  • Yellow box: visitor (student)

  • ObjectStructure aggregates grades and students. When calling, you can interact with ObjectStructure.

Role analysis

  • Achievement(): Interviewee interface

  • Chinese() / Mathematics(): Interviewee interface implementation

  • Student(): visitor interface

  • XiaoMing() / XiaoHong(): visitor interface implementation

  • ObjectStructure(): Structure object role, which is a necessary role to use the visitor model. It has the following characteristics: it can enumerate its elements; it can provide a high-level interface to allow visitors to access its elements; if necessary, it can be designed as a composite object or a collection (such as a list or unordered collection).

      我理解的ObjectStructure():避免访问者与被访问者直接交互,遵守迪米特原则
      (最少知道原则)
      
      迪米特原则定义之一:
      	一个类对自己依赖的类知道的越少越好,你的东西也别让我知道(不对外泄露信息)
    

Code

Achievement interface:

public interface Achievement {
    
    
    //分数
    void fraction();
}

Chinese language score, realize the score interface:

public class Chinese implements Achievement {
    
    
    //姓名
    private final String name;
    //分数
    private final double fraction;
    //传递姓名和分数 
    public Chinese(String name ,double fraction) {
    
    
        this.fraction = fraction;
        this.name = name;
    }
    @Override
    public void fraction() {
    
    
        Log.i("访问者模式",name+" 的语文成绩为 "+fraction+" 分");
    }
}

Mathematics math scores, realize the score interface:

public class Mathematics implements  Achievement {
    
    
    //姓名
    private final String name;
    //分数
    private final double fraction;

    public Mathematics(String name ,double fraction) {
    
    
        this.fraction = fraction;
        this.name = name;
    }
    @Override
    public void fraction() {
    
    
        Log.i("访问者模式",name+" 的数学成绩为 "+fraction+" 分");
    }
}

Student student interface, aggregate the score interface:

public interface Student {
    
    
    //具体学生
    void student(Achievement achievement);
}

XiaoMing Xiaoming, implement the student interface:

public class XiaoMing implements Student {
    
    
    @Override
    public void student(Achievement achievement) {
    
    
        //小明成绩
        achievement.fraction();
    }
}

XiaoHong, realize the student interface:

public class XiaoHong implements Student {
    
    

    @Override
    public void student(Achievement achievement) {
    
    
        achievement.fraction();
    }
}

ObjectStructure, the role of structured objects, (in compliance with the Dimit principle):

public class ObjectStructure {
    
    
    /**
     *  //输出成绩
     * @param student 具体学生
     * @param achievement 具体要除数的分数
     */
    public void outputAchievement(Student student,Achievement achievement){
    
    
            student.student(achievement);
    }
}

Test code (client):

		 //小明
        XiaoMing xiaoMing = new XiaoMing();
        //小红
        XiaoHong xiaoHong = new XiaoHong();


        //小明语文成绩
        Chinese chinese1 = new Chinese("小明",67);

        //小红语文成绩
        Chinese chinese2 = new Chinese("小红",100);

        //小明数学成绩
        Mathematics mathematics = new Mathematics("小明",43);
		
		//结构对象角色
        ObjectStructure objectStructure = new ObjectStructure();

        xiaoMing.student(chinese1);
        objectStructure.outputAchievement(xiaoMing,chinese1);
        objectStructure.outputAchievement(xiaoHong,chinese2);
        objectStructure.outputAchievement(xiaoMing,mathematics);

Log图(2.1):
Insert picture description here

How to expand

For example, now we need to add an English, a classmate named Xiao Zhang:

English English score, achieve the score interface:

public class English implements Achievement{
    
    
    //姓名
    private final String name;
    //分数
    private final double fraction;

    public English(String name ,double fraction) {
    
    
        this.fraction = fraction;
        this.name = name;
    }
    @Override
    public void fraction() {
    
    
        Log.i("访问者模式",name+" 的英语成绩为 "+fraction+" 分");
    }
}

XiaoZhang student, implement the student interface:

public class XiaoZhang implements Student {
    
    

    @Override
    public void student(Achievement achievement) {
    
    
        achievement.fraction();
    }
}

Test code (client):

 //小张
XiaoZhang xiaoZhang = new XiaoZhang();
//英语成绩
 English english = new English("小张", 55);
 
ObjectStructure objectStructure = new ObjectStructure();

objectStructure.outputAchievement(xiaoZhang,english);

Log图(2.2):
Insert picture description here
Summary:

  • Comply with the Dimit principle (only communicate with direct friends, the less a class knows about the classes it depends on, the better, and no information is leaked) This refers to ObjectStructure
  • Comply with the opening and closing principle (open for extension, closed for modification): here refers to the addition of English and Xiao Zhang extension , good scalability
  • Comply with the single responsibility principle : (One class is responsible for one responsibility, not one class is responsible for one responsibility), here refers to the implementation class corresponding to the grade/student

Complete code

Go to Design Mode Homepage/Design Principles

Originality is not easy, your likes are your greatest support for me~

Guess you like

Origin blog.csdn.net/weixin_44819566/article/details/112746412