Skip to content

访问者模式

定义

对于一组对象,在不改变数据结构的前提下增加作用于这些结构元素新的功能。

使用场景

  1. 对象结构中对象对应的类很少改变,但经常需要在此对象结构上定义新的操作
  2. 需要对一个对象结构中的对象进行很多不同的并且不相关的操作,而需要避免让这些操作"污染"这些对象的类,也不希望在增加新操作时修改这些类。
ts
interface Visitor {
  visitCPU(cpu: CPU): void;
  visitHardDisk(hardDisk: HardDisk): void;
}

class UpdateVisitor implements Visitor {
  visitCPU(cpu: CPU): void {
    cpu.command = '1 + 1 = 2';
  }
  visitHardDisk(hardDisk: HardDisk): void {
    hardDisk.command = '记住 1 + 1 = 2';
  }
}

abstract class Hardware {
  command: string;
  constructor(command: string) {
    this.command = command;
  }
  public run() {
    console.log(this.command);
  }

  public abstract accept(visitor: Visitor);
}

class CPU extends Hardware {
  constructor(command: string) {
    super(command);
  }

  public accept(visitor: Visitor) {
    visitor.visitCPU(this);
  }
}

class HardDisk extends Hardware {
  constructor(command: string) {
    super(command);
  }
  public accept(visitor: Visitor) {
    visitor.visitHardDisk(this);
  }
}

class Robot {
  private hardwares: Hardware[] = [];

  constructor() {
    this.hardwares.push(new CPU('1 + 1 = 1'));
    this.hardwares.push(new HardDisk('记住 1 + 1 = 1'));
  }

  public run() {
    this.hardwares.forEach(hardware => hardware.run());
  }

  public accept(visitor: Visitor) {
    this.hardwares.forEach(hardware => hardware.accept(visitor));
  }
}

const robot = new Robot();
robot.run();

robot.accept(new UpdateVisitor());

robot.run();