Using a strategy pattern and a command pattern

后端 未结 7 1945
隐瞒了意图╮
隐瞒了意图╮ 2020-12-02 03:56

Both design patterns encapsulate an algorithm and decouple implementation details from their calling classes. The only difference I can discern is that the Strategy pattern

相关标签:
7条回答
  • 2020-12-02 04:37

    I might be wrong in my opinion, but I treat the command as function-to-execute, or reaction. There should be at least two players: the one who requests the action, and the one who executes the action. GUI is typical example for command pattern:

    • All buttons on application toolbar are associated with some action.
    • Button is the executor in this case.
    • Action is the command in this case.

    The command is usually bounded to some scope or business area, but not necessary: you may have commands that issue a bill, start a rocket or remove a file implementing the same interface (e.g. single execute() method) within one application. Often commands are self-containing, so they don't need anything from the executor to process the task they are intend to (all necessary information is given at construction time), sometimes commands are context-sensitive and should be able to discover this context (Backspace command should know the caret position in the text to correctly remove the previous character; Rollback command should discover the current transaction to rollback; ...).

    The strategy is a bit different: it is more bound to some area. The strategy may define a rule to format a date (in UTC? locale specific?) ("date formatter" strategy) or to calculate a square for a geometric figure ("square calculator" strategy). Strategies are in this sense flyweight objects, that take something as input ("date", "figure", ...) and make some decision on its basis. Perhaps not the best, but good example of strategy is one connected with javax.xml.transform.Source interface: depending on whether the passed object is DOMSource or SAXSource or StreamSource the strategy (= XSLT transformer in this case) will apply different rules to process it. The implementation can be a simple switch or involve Chain of responsibility pattern.

    But indeed there is something in common between these two patterns: commands and strategies encapsulate algorithms within the same semantic area.

    0 讨论(0)
提交回复
热议问题