I'm creating an autocomplete functionality from scratch using Angular 2. I need to listen for different keystrokes and perform a different action depending on what keystroke is pressed. There are four types of keystrokes I must listen for: an enter press, a down arrow press, an up arrow press, and a key press that would fire a new autocomplete query (ex: backspace, alphanumeric keys, delete, something that changes the value of the string in the input text box).
My project lead wants me to implement a design pattern for creating the keystroke handlers, and recommended the factory pattern (most likely as practice with design patterns). So the theoretical factory would create a different object for each of my four types of keystrokes. The listener gives back a string that I can use to determine which key was pressed (ex "ArrowUp, "ArrowDown", "Enter"). So the enter handler would select the highlighted option and populate it into the text box. A down handler would deselect the current option and select the option below it.
What is the best way for the factory to determine which object to create. For example I could do something like:
createHandler(keystroke) {
//or alternatively use a case statement
if(keystroke === "Enter") {
return new EnterHandler();
} else if(keystroke === "ArrowDown") {
return new ArrowDownHandler();
} else if(...)
}
But after reading up on this pattern, this is a "naive" implementation. What is the best way to know which object to create based on a string passed in then for my particular case? Or is there another better pattern for the functionality I am looking for?
Aucun commentaire:
Enregistrer un commentaire