设计模式系列:访问者模式

概念

访问者模式有点复杂。一般不轻易使用。他的主要任务是通过不同的访问器,访问问相同的对象,得到不同的信息
生成不同的报表等。

实现

类图

图片

代码

  • Coputer被访问者
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
* @Description TODO
* @ClassName Computer
* @Author littlehui
* @Date 2020/4/7 18:20
* @Version 1.0
**/
public class Computer implements ComputerPart {

ComputerPart[] parts;

public Computer(){
parts = new ComputerPart[] {new Screen(), new Keyboard()};
}

public void accept(ComputerPartVisitor computerPartVisitor) {
for (int i = 0; i < parts.length; i++) {
parts[i].accept(computerPartVisitor);
}
}

}
  • ComputerPart 被访问者,被访问的部分
1
2
3
4
5
6

public interface ComputerPart {

public void accept(ComputerPartVisitor computerPartVisitor);

}
  • ComputerPartVisitor 访问者
1
2
3
4
public interface ComputerPartVisitor {
public void visit(Screen screen);
public void visit(Keyboard keyboard);
}
  • Keyboard ,Screen 具体的电脑访问部分对象
1
2
3
4
5
6
7
8
9
10
11
public class Keyboard implements ComputerPart {

public void accept(ComputerPartVisitor computerPartVisitor) {
computerPartVisitor.visit(this);
}
}
public class Screen implements ComputerPart {
public void accept(ComputerPartVisitor computerPartVisitor) {
computerPartVisitor.visit(this);
}
}
  • 访问接口 Visitor
1
2
3
4
public interface Visitor {

public void visit(ComputerPart computerPart);
}
  • Client客户端调用方式
1
2
3
4
5
6
7
public class Client {

public static void main(String[] args) {
ComputerPart computer = new Computer();
computer.accept(new ComputerPartDisplayVisitor());
}
}
  • 执行结果
1
2
3
4
5
6
Connected to the target VM, address: '127.0.0.1:51341', transport: 'socket'
this is computer screen
this is computer keyboard
Disconnected from the target VM, address: '127.0.0.1:51341', transport: 'socket'

Process finished with exit code 0

场景

访问者模式一般用于当对象属性或者信息太多,太杂的时候,通过不同的访问器(观察角度),访问不同的信息。
并且可以对信息进行二次加工。具体场景如:
1:员工的绩效评估,工程师和HR评估的角度不同。访问角度不同,这时候
访问者模式就比较适合。
2:报表,老板看到的报表和团队看到的项目报表肯定不一样。这时就满足访问者模式场景。

总结

总的来讲,访问者模式提供多角度对同个对象的观测方式。对其理解不深很深刻,总结可能不到位,以后再总结。