oop - 涉及 HTMLElements 的决策树的规则模式、状态模式或其他东西?
问题描述
我最近一直在学习设计模式,并试图了解在以下情况下规则模式、状态模式或其他东西是否是最好的:
我有代码,我想根据 HTMLElement 的 innerText 和按下的键执行特定操作。将来可能会添加更多类型的键,并在 innerText 上运行更多检查。
我一直在考虑状态和规则模式,但如果我想错了方向,我也会对其他模式持开放态度。
我会选择状态,因为 HTML 的 innerText 要么是 EMPTY、NOT EMPTY、VOCAB、MATH,而且可能有也可能没有分配给 enter 键的操作。
我会选择规则模式,因为我可以检查 keyIsEnter 和 innerTextIsEmpty
选项 A - 规则
interface Rule {
isSatisfied(innerText: string): boolean
}
class Empty implements Rule {
public isSatisfied(innerText: string): { /* code */ }
}
class NotEmpty implmenets Rule {
public isSatisfied(innerText: string): { /* code */ }
}
class Client {
public enterPressed(innerText: string): void {
if (this.empty.isSatisfied(innerText)) {
// some code
} else if (this.notEmpty.isSatisfed(innerText)) {
// some code
}
}
}
选项 B - 状态
interface State {
enterPressed(): void;
tabPressed(): void;
}
class Empty implements State {
enterPressed(): void {/* code */}
tabPressed(): void {/* code */}
}
class NotEmpty implements State {
enterPressed(): void {/* code */}
tabPressed(): void {/* code */}
}
解决方案
推荐阅读
- ruby-on-rails - 模型无效,因为创建时外键不存在
- aws-lambda - 触发错误时,New Relic 不会为进程调度 NRQL 警报条件
- sql - 错误:值 show 不是 Unit CaseFileDFTemp.show() 的成员
- javascript - 如何根据jQuery数据表中返回的数据默认选择下拉值
- excel - vba中如何判断单选框是否被选中
- vue.js - Vue 组件样式未在 Puppeteer 中加载
- react-native - 将动态文件名导入 React-Native
- redis - 在 JEDIS 中增加池大小会影响 redis 性能吗?
- git - 有没有办法让 GIT 通过历史跟踪重命名的文件
- mysql - 使用 Fetch API 使用效果删除一行 - ReactJS