I've been learning about design patterns recently and am trying to understand whether a rule pattern, state pattern, or something else is the best given the following scenario:
I have code that I want to do a specific action based upon a HTMLElement's innerText and what key is pressed. In the future there is likely to be more types of keys added and more checks run across the innerText.
I've been considering the state and rule pattern, but am also open to other patterns if I'm thinking in the wrong direction.
I would choose state because the innerText of an HTML is either EMPTY, NOT EMPTY, VOCAB, MATH, and may or may not have an action assigned to the enter key.
I would choose the rule pattern because I can check for keyIsEnter and innerTextIsEmpty
Option A - Rule
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
}
}
}
Option B - State
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 */}
}
Aucun commentaire:
Enregistrer un commentaire