前言:【模式總覽】——————————by xingoohtml
對於某個對象或者一組對象,不一樣的訪問者,產生的結果不一樣,執行操做也不一樣。此時,就是訪問者模式的典型應用了。java
應用場景node
1 不一樣的子類,依賴於不一樣的其餘對象ide
2 須要對一組對象,進行許多不相關的操做,又不想在類中是如今這些方法this
3 定義的類不多改變,可是執行的操做卻常常發生改變。spa
Context 環境角色code
class Context{ List<Node> list = new ArrayList(); public void add(Node node) { list.add(node); } public void visit(Visitor visitor) { for(Node node : list){ node.accept(visitor); } } }
Visitor 訪問者角色htm
interface Visitor{ public void visit(NodeA nodeA); public void visit(NodeB nodeB); } class VisitA implements Visitor{ public void visit(NodeA nodeA){ System.out.println("***visitA***"); nodeA.action(); } public void visit(NodeB nodeB){ System.out.println("***visitA***"); nodeB.action(); } } class VisitB implements Visitor{ public void visit(NodeA nodeA){ System.out.println("***visitB***"); nodeA.action(); } public void visit(NodeB nodeB){ System.out.println("***visitB***"); nodeB.action(); } }
Node 被訪問角色對象
interface Node{ public void accept(Visitor visitor); } class NodeA implements Node{ public void accept(Visitor visitor) { visitor.visit(this); } public void action(){ System.out.println("NodeA visited"); } } class NodeB implements Node{ public void accept(Visitor visitor) { visitor.visit(this); } public void action(){ System.out.println("NodeB visited"); } }
所有代碼blog
1 package com.xingoo.test.design.visitor; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 interface Visitor{ 7 public void visit(NodeA nodeA); 8 public void visit(NodeB nodeB); 9 } 10 class VisitA implements Visitor{ 11 public void visit(NodeA nodeA){ 12 System.out.println("***visitA***"); 13 nodeA.action(); 14 } 15 public void visit(NodeB nodeB){ 16 System.out.println("***visitA***"); 17 nodeB.action(); 18 } 19 } 20 class VisitB implements Visitor{ 21 public void visit(NodeA nodeA){ 22 System.out.println("***visitB***"); 23 nodeA.action(); 24 } 25 public void visit(NodeB nodeB){ 26 System.out.println("***visitB***"); 27 nodeB.action(); 28 } 29 } 30 interface Node{ 31 public void accept(Visitor visitor); 32 } 33 class NodeA implements Node{ 34 public void accept(Visitor visitor) { 35 visitor.visit(this); 36 } 37 public void action(){ 38 System.out.println("NodeA visited"); 39 } 40 } 41 class NodeB implements Node{ 42 public void accept(Visitor visitor) { 43 visitor.visit(this); 44 } 45 public void action(){ 46 System.out.println("NodeB visited"); 47 } 48 } 49 class Context{ 50 List<Node> list = new ArrayList(); 51 public void add(Node node) { 52 list.add(node); 53 } 54 public void visit(Visitor visitor) { 55 for(Node node : list){ 56 node.accept(visitor); 57 } 58 } 59 } 60 public class Client { 61 private static Context ctx = new Context(); 62 public static void main(String[] args) { 63 ctx.add(new NodeA()); 64 ctx.add(new NodeB()); 65 ctx.visit(new VisitA()); 66 ctx.visit(new VisitB()); 67 } 68 }
運行結果
***visitA*** NodeA visited ***visitA*** NodeB visited ***visitB*** NodeA visited ***visitB*** NodeB visited