Based on various threads on SO (ex. Replacing if else statement with pattern ) I understand that I can replace multiple if\else statements with the Command
pattern.
My situation is a bit different.
I have a series of Commands
and I need to execute each Command
only if the previous command was unsuccessful.
For example, suppose I need to retrieve text from a hypothetical page - I could scrape the text directly from the page using screen scraping or I could fetch the text from the API. I would only want to fetch the text from API if screen scraping was not successful. In other words I would only execute the "fetch" command if the "scrape" command didn't work.
In this case, I would test if the scraped String is empty or equal to null and then execute the second Command. If the second command is also unsuccessful I would execute the third Command and so on.
The important point is that we only execute subsequent commands if a certain condition is true/false. The condition is always the same for each Command but the number of commands might grow in the future.
I cannot implement this via the typically suggested route (using a Map
and Command
interface) bec this would not execute the next Command
if the first one failed (it would also be unable to check if a Command
was successful or not)
What design pattern could be used to solve this problem?
Aucun commentaire:
Enregistrer un commentaire