Reputation: 2719
There are a lot of questions on SO comparing Bridge pattern and Strategy pattern. Explanations include
Bridge is structural and Strategy is behavioral
and
UML and code look similar but the intent is different
among other less common ones.
None of those explanations I've come across here or elsewhere is satisfactory. I clearly know when I am using the Strategy pattern and Bridge pattern because of my intention and the problem I need to solve but from a distance, the distinction gets blurred. Thus, this question keeps my mind busy time to time.
If I use the Bridge pattern when modeling the structure of the components, doesn't it become Strategy pattern at runtime, naturally?
Edit: On requesti I am adding SO questions
This answer says that UML diagram and code are similar but the reason for usages may differ. This answer says that their syntaxes are similar but goals are different. This answer says that one of them is structural and the other is behavioral. This answer got very close but at the end, there is no single reason why bridge is also strategy at runtime. This answer is also a worth reading but it still begs the same question; does Bridge pattern becomes Strategy pattern at runtime? Is our intention the only difference?
Edit 2: I would like to ask it differently. Looking only a source code, let's say this Strategy Pattern example and this Bridge Pattern example, how can you tell Bridge pattern from Strategy pattern? It seems like we can swap these to sample codes and tutorials still make sense.
Upvotes: 2
Views: 817
Reputation: 17066
The superficial comparisons between Bridge and Strategy seem to focus on the composition relationship between each pattern's main components. This relationship is a spurious basis for comparison, because a majority of GoF design patterns employ composition (hence their famous principle, "Favor object composition over class inheritance.")
In contrast, note the composition relationship in a Bridge links one abstraction to another, whereas the composition relationship in a Strategy links an implementation to an abstraction. A Bridge is useful when the client depends on an (abstract) API that is implemented in terms of a separate, differing API. Strategy is useful when the client is a concrete implementation whose behavior can be modified by using multiple algorithms.
There is also a difference in the scope of abstraction between these patterns. Bridge uses one API to implement another entirely. The client API delegates all calls to the implementor (invisibly to the client). Strategy uses an API as one piece of a client implementation. A strategy does not implement the entire client API.
Summary
Bridge
Strategy
Finally, note that neither of these patterns are particularly common in modern OOP. Bridge is a niche case that requires a priori planning, while Strategy is now supported natively via lambdas or closures.
Upvotes: 3