查表法
查表法两大优势:
- 空间换时间。预计算好输入对应的输出并存入映射表,然后运行时查表避免运行时计算,竞赛选手也把这叫打表法
- 简化条件分支。将每个输入对应的分支存入映射表,然后运行时查表选择执行的分支,开发者经常使用,可以降低圈复杂度
查表法经常和其它设计模式一起使用,包括策略模式、状态模式、工厂模式
查表法+策略模式
本质上是通过查表返回策略(方法)
// HTTP状态码处理
const statusHandlers: Record<number, (response: Response) => void> = {
200: (res) => processData(res.json()),
404: () => showNotFound(),
500: (res) => logError(res.text()),
// ...
};
fetch('/api/data')
.then(response => {
const handler = statusHandlers[response.status] || handleUnknownStatus;
handler(response);
});
查表法+状态模式
本质上是通过查表返回状态(枚举值)
// 游戏物品属性表
const itemStatsTable: Record<ItemType, ItemStats> = {
[ItemType.SWORD]: { damage: 15, speed: 1.2 },
[ItemType.AXE]: { damage: 25, speed: 0.8 },
[ItemType.BOW]: { damage: 10, speed: 2.0 },
};
class Player {
equipItem(type: ItemType) {
this.weaponStats = itemStatsTable[type];
}
calculateDamage(): number {
return this.weaponStats.damage * this.strength;
}
}
查表法+工厂模式
本质上是通过查表返回对象
// 文件格式处理器查表
const fileHandlers: Record<string, FileHandler> = {
'.jpg': new ImageHandler(),
'.png': new ImageHandler(),
'.mp4': new VideoHandler(),
'.pdf': new DocumentHandler(),
'.docx': new DocumentHandler(),
};
function processFile(filename: string): void {
const ext = filename.slice(filename.lastIndexOf('.'));
const handler = fileHandlers[ext.toLowerCase()];
if (handler) {
handler.process(filename);
} else {
throw new Error(`Unsupported file type: ${ext}`);
}
}