136

I tried to read many articles on dofactory, wikipedia and many sites. I have no idea on differences between bridge pattern and the strategy pattern.

I know both of them decouple an abstraction from its implementation and can change implementation at run time.

But I still don't know in which situation I should use strategy or in which situation I should use bridge.

Hearen
  • 7,420
  • 4
  • 53
  • 63
Krirk
  • 1,466
  • 2
  • 10
  • 10

15 Answers15

82

Semantics. From wikipedia:

The UML class diagram for the Strategy pattern is the same as the diagram for the Bridge pattern. However, these two design patterns aren't the same in their intent. While the Strategy pattern is meant for behavior, the Bridge pattern is meant for structure.

The coupling between the context and the strategies is tighter than the coupling between the abstraction and the implementation in the Bridge pattern.

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.

Hearen
  • 7,420
  • 4
  • 53
  • 63
Kent Boogaart
  • 175,602
  • 35
  • 392
  • 393
  • 5
    so can I say that I am using the strategy pattern to be able to abstract behavior while also making the code look neater like in the bridge pattern.. or, I am using the Bridge pattern to make the code neater and also because it allows me to abstract behavior like in the strategy pattern? and would I be right? – user20358 Feb 08 '12 at 15:58
  • 1
    The difference between the two is only in their intent. So i guess we could safely say that, because both of them use the same idea and offer the same flexibility, the two patterns are functionally the same. – Elz Sep 04 '15 at 07:22
  • 5
    [Bridge's UML](http://www.plantuml.com/plantuml/img/bL4nRiCm3Dpv2i9Tx24VI0C3iG47cGfqBJeeDfqAbKH3OWSZyDyhstMX1XtQJUJnU7UYQ364bTVTbJ0_SLD0UDTkK5vP3396C8ZNhNnO0s-w8oGxo8YMx8Ly07M9i6e5MwD2mEDNgTdX3H2V1l9ghl829d0iX8PwGUxJqVq-dTDss9NVZRCTyk8Ho7Kuqs7LUQPUE-fIkKWpPCd9lOi9G3iXtwkMyBnDiLyCthO04_wKZBHLgcRNUX9AcCTKx7xZtzTK_re3QQeiCZFaNPdoO3rGY5c9PHmeEUMyifwDLEmxyZKRzeT3mroM-73rD6vumqv-GRSOMMrq5CjGnKZBSvkRFthjuEvb8Rr6UudfJm00) is quite **different** in my copy of the GoF book. [This tool](http://users.encs.concordia.ca/~nikolaos/pattern_detection.html) is able to distinguish Bridge from Strategy. – Fuhrmanator Aug 08 '16 at 18:03
  • 1
    Wikipedia is often a terrible reference. Rightly, that misinformation was removed from the page. https://en.wikipedia.org/w/index.php?title=Strategy_pattern&oldid=516390466 – Fuhrmanator Aug 08 '16 at 18:26
  • It's worth mentioning that while strategy pattern handles one function which can be replaced at runtime, the bridge pattern can have multiple functions that each class overrides them differently. ie. Appliance interface with ON and OFF methods - you solve it with Bridge pattern – TheLogicGuy Jan 23 '18 at 16:45
  • 2
    The way I get it is that the same technique is used to abstract an implementation (strategy) or to abstract an interface (bridge). Strategy swaps behaviors, Bridge swaps interfaces (this ultimately allows implementations with such interfaces to be swaped). In other words Bridge creates standardized interface on one side and plugs implementations with different interfaces on the other. – Nikaas Feb 17 '18 at 18:17
  • If the UML diagram is the same that means one of two things: 1: They are the same thing. 2: One of the UML diagrams is wrong or missing some crucial element. I do not know which of those two cases it is. – FreelanceConsultant Sep 20 '22 at 08:20
  • In other words, the intent is irrelevant. If the UML is the same, then they are the **same thing**, and that **one thing** can help you in multiple ways. To say the UML is the same but they are **different** things would be to argue that `std::vector` is two different things because it **can** grow dynamically and because it **can** have an initial `> 0` capacity. – FreelanceConsultant Sep 20 '22 at 08:22
  • I suspect they are fundamentally **different** in some important way but I don't at present understand what that is. – FreelanceConsultant Sep 20 '22 at 08:24
64

The Bridge pattern is a structural pattern (HOW DO YOU BUILD A SOFTWARE COMPONENT?). The Strategy pattern is a dynamic pattern (HOW DO YOU WANT TO RUN A BEHAVIOUR IN SOFTWARE?).

The syntax is similar but the goals are different:

  • Strategy: you have more ways for doing an operation; with strategy, you can choose the algorithm at run-time and you can modify a single Strategy without a lot of side-effects at compile-time;
  • Bridge: you can split the hierarchy of interface and class, join it with an abstract reference (see explication)
Hearen
  • 7,420
  • 4
  • 53
  • 63
alepuzio
  • 1,382
  • 2
  • 28
  • 38
  • 3
    so if the syntax is similar would I be correct in saying that I am using either of those patterns to run a software behavior a particular way and also because I want to build the component in that fashion so it looks neat as well? – user20358 Feb 08 '12 at 15:55
21

I was thinking the same, but recently I had to use bridge and realized that bridge is using strategy and adding abstraction to the context so that you later can make more changes without changing the client. When using Strategy without the abstraction the design is not as flexible and may require changes to the client later. But when using the whole bridge the design becomes even more flexible. Here you can se how going from Strategy to Bridge gives more flexibility. Also we assume that now "visa" and "master" are not only available on cards but on phones and chips also; and if we use bridge it is much easier to add that support.

Strategy VS Bridge

Orhan
  • 1,395
  • 13
  • 12
12

Strategy:

  • Context tied to the Strategy: The context Class (possibly Abstract but not really an interface! as u wish to encapsulate out a specific behavior and not the entire implementation) would know/contain the strategy interface reference and the implementation to invoke the strategy behavior on it.
  • Intent is ability to swap behavior at runtime

    class Context {
    
         IStrategy strategyReference;
    
         void strategicBehaviour() {
    
            strategyReference.behave();
         }
    
    }
    

Bridge

  • Abstraction not tied to the Implementation: The abstraction interface (or abstract class with most of the behavior abstract) would not know/contain the implementation interface reference
  • Intent is to completely decouple the Abstraction from the Implementation

    interface IAbstraction {
    
        void behaviour1();
    
        .....
    
    }
    
    interface IImplementation {
    
         void behave1();
    
         void behave2();
    
         .....
    
    }
    
    class ConcreteAbstraction1 implements IAbstraction {
    
          IImplementation implmentReference;
    
          ConcreteAbstraction1() {
    
               implmentReference = new ImplementationA() // Some implementation
    
          }
    
          void behaviour1() {
    
                implmentReference.behave1();
    
          }
    
          .............
    
    }
    
    class ConcreteAbstraction2 implements IAbstraction {
    
          IImplementation implmentReference;
    
          ConcreteAbstraction1() {
    
               implmentReference = new ImplementationB() // Some Other implementation
    
          }
    
          void behaviour1() {
    
                implmentReference.behave2();
    
          }
    
          .............
    
    }
    
Eva
  • 4,397
  • 5
  • 43
  • 65
MEER
  • 129
  • 1
  • 2
9

Bridge: ( A structural pattern)

Bridge pattern decouples abstraction and implementation and allows both to vary independently.

Use this pattern when :

  1. Abstractions and implementations have not been decided at compile time
  2. Abstractions and implementations should be changed independently
  3. Changes in implementation of abstraction should not affect caller application
  4. Client should be insulated from implementation details.

Strategy: ( Behavioural pattern)

Strategy patterns enable you to switch between multiple algorithms from a family of algorithms at run time.

Use Strategy pattern when :

  1. Multiple versions of algorithms are required
  2. The behaviour of class has to be changed dynamically at run time
  3. Avoid conditional statements

Related posts:

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

Real World Example of the Strategy Pattern

Ravindra babu
  • 37,698
  • 11
  • 250
  • 211
4

Design pattern types

  • Behavioural: patterns characterise the ways in which classes or objects interact and distribute responsibility
  • Structural: patterns deal with the composition of classes or objects.
  • Creational : patterns are concerned about the process of object creation.

Bridge (Structural)

Decouple an abstraction from its implementation so that each may vary. independently. enter image description here

Take a remote. The remote has buttons 1-6. This is the concrete class in the diagram above. Each button will work different depending on if the remote is used for a TV or DVD. The functionality for each button is abstracted from the implementation by the implementer interface.

This allows us to change how the remote will work for each device.

Strategy (Behavioural)

Define a family of algorithms , encapsulate each one and make them interchangeable. enter image description here

In strategy, if we were looking at the remote scenario. The "state" is the entire remote which we swap out by changing the context's state reference. The "concreteStateA" (TV remote) "concreteStateB" (DVD Remote).

Additional reading:

Daniel
  • 2,028
  • 20
  • 18
3
  1. Strategy Pattern is used for Behavioural decisions, while Bridge Pattern is used for Structural decisions.

  2. Brigde Pattern separats the abstract elements from the implementation details, while Strategy Pattern is concerned making algorithms more interchangeable.

Strategy Pattern in UML

Brigde Pattern in UML

Strategy Pattern in Swift:

protocol PrintStrategy {
   func print(_ string: String) -> String
}

class Printer {
   let strategy: PrintStrategy

   init(strategy: PrintStrategy) {
      self.strategy = strategy
    }

  func print(_ string: String) -> String {
     return self.strategy.print(string)
  }
}

class UpperCaseStrategy: PrintStrategy {
    internal func print(_ string: String) -> String {
        return string.uppercased()
    }
}

class LowerCaseStrategy: PrintStrategy {
    internal func print(_ string: String) -> String {
        return string.lowercased()
    }
}

var lower = Printer(strategy: LowerCaseStrategy())
lower.print("I love Software Patterns")

var upper = Printer(strategy: UpperCaseStrategy())
upper.print("I love Software Patterns")

Brigde Pattern in Swift:

protocol Appliance {
   func run()
}

protocol Switch {
   let appliance: Appliance {get set}
   func turnOn()
}

class RemoteControl: Switch {
   var appliance: Appliance

   init(appliance: Appliance) {
       self.appliance = appliance
   }

   internal func turnOn() {
      appliance.run()
   }
}

class TV: Appliance {
   internal func run() {
      print("TV is ON")
   }
}

class Stereo: Appliance {
   internal func run() {
      print("Stereo is ON")
   }
}

var tvRemote = RemoteControl.init(appliance: TV())
tvRemote.turnOn()

var stereoRemote = RemoteControl.init(appliance: Stereo())
stereoRemote.turnOn()
Joan Disho
  • 31
  • 2
  • how come only strategy pattern is more "interchangable". Since we code to interface, not to implementation, we can swap the implementations in strategy, or bridge, as you demonstrated in your code example, swapping `Stereo` with `TV` and the code just works. – denis631 Dec 25 '19 at 13:21
  • In the Bridge Pattern, something inherits from a base class on the left hand side. But what is the consequence of this? In what way does this make it *different* to the Strategy pattern. What is the importance of having a base class and a derived class, rather than just a single class on the left. – FreelanceConsultant Sep 20 '22 at 08:45
2

Adding to willcodejavaforfood's answer, they can be the same, in implementation. However you use strategy to swap strategies such as sorting strategy, while you use bridge to bridge the implementations of two object's say a database wrapper, and a network adaptor so the client code can use either working against the same API. So the naming actually says it all

Robert Gould
  • 68,773
  • 61
  • 187
  • 272
1

Strategy pattern is used when you wish to plug algorithm or strategy at run time. As category of pattern also implies that it deals with behaviour of the objects. On the other hand bridge is structural pattern and deals with structural hierarchy of the objects. It decouples the abstraction from implementation by introducing a refined abstraction between them. Refined abstraction can be confused with the run time strategy plugged (In Strategy pattern). Bridge pattern deals with the structural aspects by providing a mechanism to avoid creating n number of classes.

1

For strategy pattern only the implementation varies.

Suppose, class A is using class B which has multiple implementations available. So in that case B would be abstract with actual implementation provided at runtime. This is strategy pattern

Now if A itself is abstract. Both A and B may vary. You would use Bridge pattern.

1

From the wiki on Strategy pattern

The UML class diagram for the Strategy pattern is the same as the diagram for the Bridge pattern. However, these two design patterns aren't the same in their intent. While the Strategy pattern is meant for behavior, the Bridge pattern is meant for structure.

The coupling between the context and the strategies is tighter than the coupling between the abstraction and the implementation in the Bridge pattern.

willcodejavaforfood
  • 43,223
  • 17
  • 81
  • 111
1

Just to add to what has already been said about the pattern comparison (difference of intent, ...): the Bridge pattern is also intentionally structured to allow the abstraction hierarchy side to vary. In languages like C# this could imply you have an abstraction base that contains virtual methods as a way to allow intended variations that don't cause problems for existing consumers. Other than that the two patterns might appear identical for the most part.

Burt
  • 73
  • 6
0

I think there's a slight difference between them in the context they're being used.

I use the Bridge pattern to separate orthogonal concepts which they both belong to a bigger one - to let them vary independently. It usually involves multiple abstractions.

IMO, the Strategy pattern is simpler or more flat. It serves to OCP for sure but doesn't necessarily to be part of another and bigger concept like the Bridge pattern.

stdout
  • 2,471
  • 2
  • 31
  • 40
0

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.

Viplove Dev
  • 15
  • 1
  • 6
0

In addition to use case differences explained by other answerers there is other thing to think of.

Seem like Bridge is a combination of Strategy and Template method behavioral patterns. So, we call methods in the same order as in Template method and change its behavior depending on given implementer as in Strategy pattern.

Doesn't it mean that two behavioral patterns along create a structural pattern? Either could we use Bridge pattern in behavioral way?