首页 > 解决方案 > 涉及 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 */}
}

标签: oopdesign-patterns

解决方案


推荐阅读