Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bridge- vs Strategy-Pattern

I know, this question was asked many times, but I did some research and still don't get it, probably you can help me out: As stated many times, the UML is almost the same. Also the implementation and idea is more or less the same: Instead of sub-typing, you define an Interface, which encapsulates some logic and let's it pass to an abstract. So, even the Microsoft-Blog guys

https://blogs.msdn.microsoft.com/gyanjadal/2015/01/05/difference-between-strategy-and-bridge-patterns/ says:

The simple answer is “They are similar but different”. The implementations are similar but the intentions are different. To give an analogy, a city bus and school bus are both similar vehicles, but they are used for different purposes. One is used to transport people between various parts of the city as a commuter service. The other is used for transporting kids to schools.

"If it sounds like a duck and looks like a duck but it intends to be a swan, it can be either of them", which is what I read here.

Since I still did't get it, so I digged deeper:

https://social.msdn.microsoft.com/Forums/en-US/08775d39-2de0-4598-8872-df21f681b7b3/strategy-vs-bridge-patterns?forum=architecturegeneral

This Thread also doesn't add anything new, except:

They both look the same on the surface to me as well. The main difference I see is the fact that in the Bridge pattern, the abstraction is PART OF the object, but in the Strategy pattern the abstraction is performed BY the object.

But, if we read the definition of strategy:

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.

There is nothing defined, how the Strategy is applied. It could also easily be an Interface on the Abstract, exactly the same the common Strategy-Implementation as LINQ-Orderby etc.

Another interest take on the topic is here:

http://game-engineering.blogspot.ch/2008/07/bridge-pattern-vs-strategy-pattern.html

The mainpart from this excourse:

You say "Strategy" when you want to vary behavior, and you do so not by writing different objects but by introducing a class heirarchy. You say "Bridge" when you expect that you will vary both the interface and the implementation. In both cases you're providing flexibility for a changing implementation; in a Bridge, you're also expecting the interface to change.

Is this probably the main-difference? Since the Implementor and the Abstraction are so loose coupled, I can change the Interface of the Implementor and the Abstraction doesn't have to care? That sounds reasonable, but wouldn't then have the Abstraction to change as well, since they are kindahow connected? Wouldn't that destroy all other principles like Information hiding and DRY?

I also looked at many many examples, which I don't add here for the sake of place, and I couldn't find an Example of either of those patterns I couldn't change to fit the other one. Be it via an Interface-Property or just an Parameter.

Did I miss anything here? Does probably anyone have a REAL-LIFE example of "I wanted to use Strategy, but the Bridge did just fit better", or visa versa, example?

Edit: Why do I justify an own Thread for this Topic (again)? First of all, the accepted answer of the mentioned Thread is the following

As I understand it, you're using the strategy pattern when you're abstracting behavior that could be provided from an external source (eg. config could specify to load some plugin assembly), and you're using the bridge pattern when you use the same constructs to make your code a bit neater. The actual code will look very similar - you're just applying the patterns for slightly different reasons.

I already provided in the previous explanations, that abstracting behavior from external source is exactly the definition of Strategy- and Bridge-Pattern.

Also

and you're using the bridge pattern when you use the same constructs to make your code a bit neater.

Also the strategy pattern makes the code way neater, since it abstracts an whole building block away, thus thightens the Code quite a bit.

I think anyone, who read the whole topic sees, that there is more on this topic just than this 2 sentences.

like image 505
Matthias Müller Avatar asked Aug 07 '16 13:08

Matthias Müller


People also ask

What is Bridge pattern used for?

The bridge pattern is a design pattern used in software engineering that is meant to "decouple an abstraction from its implementation so that the two can vary independently", introduced by the Gang of Four.

What is the difference between strategy and decorator pattern?

The strategy pattern allows you to change the implementation of something used at runtime. The decorator pattern allows you augment (or add to) existing functionality with additional functionality at run time.

What is the difference between strategy and template design pattern?

But, the key difference is that Strategy Pattern is about modifying a behaviour of a context in runtime using strategies, while Template Method Pattern is about following a skeleton implementation of an algorithm and modifying its behaviour by overriding methods of the skeleton class in the subclasses.


3 Answers

In the Strategy pattern, the activities of the "Parent" for a particular operation are constant whereas the activities of the "Child" can vary. However, in the Bridge Pattern, the activities of the Parent, as well as the Child, can vary.

So, for example,

public class Ticket {
    
    Date dateOfTravel;
    int distance;
    Vehicle vehicle;
    Seat  seat;
    
    public float getTotalFare(){
         //depends on 
               //Distance
               //Vehicle - whether Vehicle is AC or non-AC. 
               //Seat - based on the location of the Seat.
     
        //Fare = vehicleBaseFare*seatMultiplier*distance

    }
    
}

In the above, the variations depend on the Parent (distance) as well as the children (Vehicle and Seat). So, here Vehicle and Seat both acted like Bridge.

Now, here

public class Vehicle {

   TrackingDevice device;

   public Coordinates getCoordinates(){
       return device.getCoordinates();
   }
}

Here, the Parent's role was constant, i.e., nothing! So, this was a Strategy pattern.

like image 120
Viplove Dev Avatar answered Sep 29 '22 22:09

Viplove Dev


Wikipedia UML Diagram for Bridge Pattern:

Wikipedia UML Diagram for BridgeHave a look at my answer in linked question for basic differences :

What is the difference between the bridge pattern and the strategy pattern?

Main difference: Abstraction and Implementation can change independently.

Regarding your other queries:

Is this probably the main-difference? Since the Implementor and the Abstraction are so loose coupled, I can change the Interface of the Implementor and the Abstraction doesn't have to care? That sounds reasonable, but wouldn't then have the Abstraction to change as well, since they are kindahow connected?

Have a look at below code example @

When do you use the Bridge Pattern? How is it different from Adapter pattern?

Even though the example is in java, it can be easily understood for c# developers.

In linked example:

Vehicle            : Abstraction
Car                : Re-defined Abstraction
Truck              : Re-defined Abstraction
Implementor        : GearShifter
ConcreteImplementor: ManualGearShifter  
ConcreteImplementor: AutoGearShifter 

Keynotes:

  1. Now Vehicle and GearShifter can change independently.

  2. If Vehicle changes, only Car and Truck have to be changed.

  3. If GearShifter changes, only ManualGearShifter and AutoGearShifter need to change.

  4. Since Vehicle(abstraction) contains GearShifter(implementation) through composition, changes in GearShifter does not affect Vehicle

  5. Since GearShifter ( implementor) does not contain or refer Vehicle ( abstraction), changes in abstraction does not effect implementation.

EDIT:

Bridge pattern presents two orthogonal class hierarchies - One is for Abstraction and one is for Implementor, which can be changed independently without dependency on other.

like image 32
Ravindra babu Avatar answered Sep 29 '22 23:09

Ravindra babu


I checked original design patterns book to see how the authors were defining Bridge pattern. Their real-life examle shows a case when both abstraction and imlementation hierarchies can change independently (i.e. new subclasses can be introduced for an abstraction; new subclasses can be introduced for implementations). Their example deals with window library that can work for different window systems. In the original example the authors used different window system from IBM, but I believe a good current analogy would be different Linux window managers (GNOME, KDE, etc.). So, imagine a Window abstraction, and two implementations for GNOME and KDE. And now imagine that you want to add new Window subclass, TransparentWindow. TransparentWindow extends Window, so as GNOMEWindow and KDEWindow. But you also have to provide imlementations for TransparentWindow: GNOMETransparentWindow and KDETransparentWindow. The hierarchy starts looking messy. Imagine new type of window, or new window manager - XFCE. To avoid complicated hierarchies, they introduce the Bridge pattern, and make two hierarchies separate (i.e. TransparentWindow extends Window; GNOMEWindow and KDEWindow extend WindowImpl). To me it seems that a tricky part is to define interface for implementation, since the hierarchies of abstractions will need to define their operations using only that interface. A learning example of Bridge pattern that I liked is here, and I liked it because it does not use artificial classes ConcreteImplementor1 and ConcreteImplementor2. When it comes to real-life examples, I believe I saw this pattern in Selenium WebDriver implementation, but I am not 100% sure now.

like image 25
oldbam Avatar answered Sep 30 '22 00:09

oldbam