实现说明
活动部件是类 KeyValueStore、MemoryStore。
演示用的数据放在这几个模块级绑定中:store。
使用要点
- 每一步打印都带着自己的标签:
read:、missing:。
常见问题
有第三方依赖吗?
没有。依赖清单是空的,代码只用标准库。 跨调用保留的状态放在这些顶层绑定里:store。
核心语句
return this.table.get(this.qualified(key)) ?? null;
private table = new Map<string, string>();
return `${this.prefix}:${key}`;
代码示例
// 抽象基类(abstract base class):契约方法由子类补齐,共享逻辑留在基类
abstract class KeyValueStore {
protected prefix: string;
constructor(prefix: string) {
this.prefix = prefix;
}
abstract get(key: string): string | null;
qualified(key: string): string {
return `${this.prefix}:${key}`;
}
}
class MemoryStore extends KeyValueStore {
private table = new Map<string, string>();
constructor() {
super('mem');
}
override get(key: string): string | null {
return this.table.get(this.qualified(key)) ?? null;
}
set(key: string, value: string): void {
this.table.set(this.qualified(key), value);
}
}
const store = new MemoryStore();
store.set('token', 'abc123');
console.log('read:', store.get('token'));
console.log('missing:', store.get('absent'));