import { ComputerPartVisitor } from "./ComputerPartVisitor"; import Mouse from "./Mouse"; import Keyboard from "./Keyboard"; import Monitor from "./Monitor"; import { ComputerPart } from "./ComputerPart";
export default class Computer implements ComputerPart {
private parts: ComputerPart[]; public name: string; constructor() { this.parts = [new Mouse(), new Keyboard(), new Monitor()]; this.name = "Computer"; }
public accept(computerPartVisitor: ComputerPartVisitor): void { for (let i = 0; i < this.parts.length; i++) { this.parts[i].accept(computerPartVisitor); } computerPartVisitor.visit(this); } }
ComputerPartVisitor.ts 访问者的接口
1 2 3 4 5 6 7 8
import Computer from "./Computer"; import Mouse from "./Mouse"; import Keyboard from "./Keyboard"; import Monitor from "./Monitor";
import { ComputerPartVisitor } from "./ComputerPartVisitor"; import Computer from "./Computer"; import Mouse from "./Mouse"; import Keyboard from "./Keyboard"; import Monitor from "./Monitor";
export default class ComputerPartDisplayVisitor implements ComputerPartVisitor { public visit(obj: Computer | Mouse | Keyboard | Monitor): void {//JavaScript中没有重载 console.log(obj.name) if (obj.name === "Computer") { console.log("Displaying Computer.");
} else if (obj.name === "Mouse") {
console.log("Displaying Mouse."); } else if (obj.name === "Keyboard") {
import { ComputerPart } from "./ComputerPart"; import Computer from "./Computer"; import ComputerPartDisplayVisitor from "./ComputerPartDisplayVisitor";
const computer: ComputerPart = new Computer(); computer.accept(new ComputerPartDisplayVisitor());