在结构不变的情况下动态改变对于内部元素的动作。 这个设计模式用的很少,且特殊。
编译器的例子: 编译器的抽象语法树进行语法分析,在语法分析的时候会用到Visitor模式。
内部结构固定的情况下使用visitor. 下面的Computer 类就是固定的(假设Computer只有三种组成)。visitor模式只适用于内部结构固定的。
package com.qqlindy.visitor;public class Computer {ComputerPart cpu = new CPU();ComputerPart memory = new Memory();ComputerPart board = new Board();public void accept(Visitor v){this.cpu.accept(v);this.memory.accept(v);this.board.accept(v);}public static void main(String[] args) {PersonelVisitor p = new PersonelVisitor();new Computer().accept(p);System.out.println(p.totalPrice);}
}abstract class ComputerPart{abstract void accept(Visitor v);abstract double getPrice();
}class CPU extends ComputerPart{@Overridevoid accept(Visitor v) {v.visitCpu(this);}@Overridedouble getPrice() {return 500;}
}class Memory extends ComputerPart{@Overridevoid accept(Visitor v) {v.visitMemory(this);}@Overridedouble getPrice() {return 300;}
}class Board extends ComputerPart{@Overridevoid accept(Visitor v) {v.visitBoard(this);}@Overridedouble getPrice() {return 200;}
}interface Visitor{void visitCpu(CPU cpu);void visitMemory(Memory memory);void visitBoard(Board board);
}class PersonelVisitor implements Visitor{double totalPrice = 0.0;@Overridepublic void visitCpu(CPU cpu) {totalPrice += cpu.getPrice()*0.9;}@Overridepublic void visitMemory(Memory memory) {totalPrice += memory.getPrice()*0.85;}@Overridepublic void visitBoard(Board board) {totalPrice += board.getPrice()*0.95;}
}class CorplVisitor implements Visitor{double totalPrice = 0.0;@Overridepublic void visitCpu(CPU cpu) {totalPrice += cpu.getPrice()*0.6;}@Overridepublic void visitMemory(Memory memory) {totalPrice += memory.getPrice()*0.75;}@Overridepublic void visitBoard(Board board) {totalPrice += board.getPrice()*0.75;}
}