本文主要是介绍访问者模式-Visitor,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
主要解决:稳定的数据结构和易变的操作耦合问题。
典型应用:编译器 Abstract Syntax Tree 抽象语法树
public class Computer {ComputerPart cpu = new CPU();ComputerPart memory = new Memory();ComputerPart board = new Board();public void acccept(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().acccept(p);System.out.println(p.totalPrice);}
}abstract class ComputerPart {abstract void accept(Visitor v);//some other operations eg:getName getBrandabstract 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 CorpVisitor 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;}
}
这篇关于访问者模式-Visitor的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!