Search code examples
design-patternsstrategy-patternchain-of-responsibility

What's the difference between "Chain of responsibility" and "Strategy" patterns?


I'm raising this question because of another question I asked here on SO some days ago.
I had to solve an specific problem, and after two replies I got, I realized two patterns can help to solve that problem (and any other similar).

  1. Chain of Responsibility
  2. Strategy

My question is:

What exactly is the difference between those patterns?


Solution

  • They're very different.

    Strategy is about having a generic interface which you can use to provide different implementations of an algorithm, or several algorithms or pieces of logic which have some common dependencies.

    For instance, your CollectionSorter could support a SortingStrategy (merge sort, quick sort, bubble sort). They all have the same interface and purpose, but can do different things.

    In some cases you may decide to determine strategy inside. Maybe the sorter has some heuristics based on collection size etc. Most of the time it indeed is injected from outside. This is when the pattern really shines: It provides users the ability to override (or provide) behavior.

    This pattern is base of the now-omnipresent Inversion of Control. Study that next once you're done with the classic patterns.

    Chain of responsibility is about having a chain of objects which usually go from more detailed to more generic. Each of the pieces in chain can provide the answer, but they have different levels of detail.

    Popular GOF example is a context help system. When you click on a component in your desktop app, which help to display? First item in chain could look for help for the very component you clicked. Next in chain could try and display help for the whole containing dialog. Next for the application module... and so on.

    Looks like you haven't, but should, read the GOF "Design Patterns" classic.