Using a strategy pattern and a command pattern

后端 未结 7 2118
隐瞒了意图╮
隐瞒了意图╮ 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:17

    For me, the difference is one of intent. The implementations of both patterns are pretty similar, but have different purposes:

    • For a Strategy, the component using the object knows what the object does (and will use it to perform a part of its own work), but it doesn't care how it does it.

    • For a Command, the component using the object knows neither what the Command does nor how it does it - it just knows how to invoke it. The caller's task is just to run the command - the processing carried out by the Command doesn't form part of the caller's core work.

    This is the difference - does the object using the component actually know or care about what the component does? Most of the time this can be determined based on whether the pattern object returns a value to its invoker. If the invoker cares about what the pattern object does then it will probably want it to return something and it will be a Strategy. If it doesn't care about any return value it is probably a Command (note, something like a Java Callable is still a Command because, although it returns a value, the caller doesn't care about the value - it just passes it back to whatever originally supplied the Command).

提交回复
热议问题