1.基本概念
- 使用一个访问者类,改变元素类的执行算法,通过这种方式,元素的执行算法可以随着访问者改变而改变
- 目的:将数据结构与数据操作分离
- 应用实例:您在朋友家做客,您是访问者,朋友接受您的访问,您通过朋友的描述,然后对朋友的描述做出一个判断,这就是访问者模式。
- UML
2.代码实现
1 package com.chengjie; 2 3 interface ComputerPart1 { 4 public void accept(ComputerPartVisitor computerPartVisitor); 5 } 6 7 class KeyBoard implements ComputerPart1 { 8 @Override 9 public void accept(ComputerPartVisitor computerPartVisitor) { 10 computerPartVisitor.visit(this); 11 } 12 } 13 14 class Monitor implements ComputerPart1 { 15 16 @Override 17 public void accept(ComputerPartVisitor computerPartVisitor) { 18 computerPartVisitor.visit(this); 19 } 20 } 21 22 class Mouse implements ComputerPart1 { 23 24 @Override 25 public void accept(ComputerPartVisitor computerPartVisitor) { 26 computerPartVisitor.visit(this); 27 } 28 } 29 class Computer1 implements ComputerPart1 { 30 31 ComputerPart1[] parts; 32 33 public Computer1(){ 34 parts = new ComputerPart1[] {new Mouse(), new KeyBoard(), new Monitor()}; 35 } 36 37 38 @Override 39 public void accept(ComputerPartVisitor computerPartVisitor) { 40 for (int i = 0; i < parts.length; i++) { 41 parts[i].accept(computerPartVisitor); 42 } 43 computerPartVisitor.visit(this); 44 } 45 } 46 47 interface ComputerPartVisitor { 48 public void visit(Computer1 computer); 49 public void visit(Mouse mouse); 50 public void visit(KeyBoard keyboard); 51 public void visit(Monitor monitor); 52 } 53 54 class ComputerPartDisplayVisitor implements ComputerPartVisitor { 55 @Override 56 public void visit(Computer1 computer) { 57 System.out.println("Displaying computer!"); 58 } 59 60 @Override 61 public void visit(Mouse mouse) { 62 System.out.println("Displaying Mouse."); 63 } 64 65 @Override 66 public void visit(KeyBoard keyboard) { 67 System.out.println("Displaying Keyboard."); 68 } 69 70 @Override 71 public void visit(Monitor monitor) { 72 System.out.println("Displaying Monitor."); 73 } 74 } 75 76 public class TestVisitor { 77 public static void main(String[] args) { 78 Computer1 comp = new Computer1(); 79 comp.accept(new ComputerPartDisplayVisitor()); 80 } 81 }
3.优点
- 符合单一职责原则
- 优秀的扩展性
4.缺点
- 具体元素对访问者暴露细节,违反迪米特原则
- 违反了依赖倒置原则,依赖了具体类
5.应用场景
- 对象结构中对象对应的类很少改变,但经常需要在此对象结构上定义新的操作
6.参考
http://www.runoob.com/design-pattern/visitor-pattern.html
来源:https://www.cnblogs.com/forTheDream1991/p/10496542.html