← 中文资源

简体中文版本

readonly 修饰符保护工厂入参

工厂把参数标成 readonly 视图,内部自建 Map 聚合而从不改写入参:排序、push 等变异方法在编译期就消失,共享表在多个工厂之间传递也不会被悄悄改掉。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

cpu total: 3
gpu total: 5
input untouched: 3 2

实现说明

WeightTable承担全部实现。 本示例的循环部分是 for (const { key, weight } of entries)。 演示用的数据放在这几个模块级绑定中:table。

使用要点

  • 直接运行文件,输出会带上标签,比如 cpu total:、gpu total:、input untouched:——输出的每一行都能指回产生它的那次调用。

常见问题

有语言之外需要解析的导入吗?

没有。每个导入都解析到语言自带的模块。 文件的状态由几个模块级绑定持有:table。

核心语句

return this.byKey.get(key) ?? 0;
map.set(key, (map.get(key) ?? 0) + weight);
const map = new Map<string, number>();

代码示例

type Entry = { key: string; weight: number };

// The factory treats both parameters as read-only views:
// the class below re-derives its own structures instead of mutating inputs.
class WeightTable {
  private readonly byKey: ReadonlyMap<string, number>;

  constructor(entries: readonly Entry[]) {
    const map = new Map<string, number>();
    for (const { key, weight } of entries) {
      map.set(key, (map.get(key) ?? 0) + weight);
    }
    this.byKey = map;
  }

  weightOf(key: string): number {
    return this.byKey.get(key) ?? 0;
  }
}

const shared: readonly Entry[] = [
  { key: 'cpu', weight: 2 },
  { key: 'gpu', weight: 5 },
  { key: 'cpu', weight: 1 },
];

const table = new WeightTable(shared);
console.log('cpu total:', table.weightOf('cpu'));
console.log('gpu total:', table.weightOf('gpu'));
console.log('input untouched:', shared.length, shared[0].weight);

// These fail compilation — readonly hides the mutating methods:
// shared.sort((a, b) => b.weight - a.weight);
// shared.push({ key: 'io', weight: 3 });