Abstract Base Classes Enforce Contracts
Force subclasses to implement storage contracts with abstract members while concrete helpers on the base class keep shared logic in one place.
Code
// 抽象基类(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'));How it works
Abstract Base Classes Enforce Contracts reduces to the classes KeyValueStore and MemoryStore.
Top-level bindings store hold the demo state — nothing sits inside a function scope.
Applying it
The demo output is labeled (read:, missing:), so each printed line maps back to the step behind it.
Statements that matter
return this.table.get(this.qualified(key)) ?? null;
private table = new Map<string, string>();
return `${this.prefix}:${key}`;
Interactive Tools for This Topic
Number Base ConverterConvert arbitrary-size integers between binary, octal, decimal, hexadecimal, and base 36 with digit validation and signed input support.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Are there third-party dependencies?
- No. The dependency list is empty; the code stays inside the standard library. Its state lives in module-level bindings: `store`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.