标签:具体类 访问 细节 pack 描述 print www mamicode void
1.基本概念
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
标签:具体类 访问 细节 pack 描述 print www mamicode void
原文地址:https://www.cnblogs.com/forTheDream1991/p/10496542.html