Difference between Bridge pattern and Adapter pattern

Design PatternsAdapterBridge

Design Patterns Problem Overview


What is the difference between the Bridge and Adapter patterns?

Design Patterns Solutions


Solution 1 - Design Patterns

> "Adapter makes things work after they're designed; Bridge makes them > work before they are. [GoF, p219]"

Effectively, the Adapter pattern is useful when you have existing code, be it third party, or in-house, but out of your control, or otherwise not changeable to quite meet the interface you need it to. For instance, we have a SuperWeaponsArray which can control a fine array of doomsday devices.

public class SuperWeaponsArray {
  /*...*/

  public void destroyWorld() {
    for (Weapon w : armedWeapons) {
      w.fire();
    }
  }
}

Great. Except we realize we have a nuclear device in our arsenal that vastly predates the conversion to the Weapon interface. But we'd really like it to work here... so what do we do... wedge it in!

NukeWeaponsAdaptor - based off of our Nuke class, but exporting the Weapon interface. Sweet, now we can surely destroy the world. It seems like bit of a kludge, but it makes things work.


The Bridge pattern is something you implement up front - if you know you have two orthogonal hierarchies, it provides a way to decouple the interface and the implementation in such a way that you don't get an insane number of classes. Let's say you have:

MemoryMappedFile and DirectReadFile types of file objects. Let's say you want to be able to read files from various sources (Maybe Linux vs. Windows implementations, etc.). Bridge helps you avoid winding up with:

MemoryMappedWindowsFile MemoryMappedLinuxFile DirectReadWindowsFile DirectReadLinuxFile

Solution 2 - Design Patterns

http://en.wikipedia.org/wiki/Adapter_pattern

The Adapter pattern is more about getting your existing code to work with a newer system or interface.

If you have a set of company-standard web service APIs that you'd like to offer to another application's existing extensibility interface, you might consider writing a set of adapters to do this. Note that there's a grey area and this is more about how you technically define the pattern, since other patterns like the facade are similar.

http://en.wikipedia.org/wiki/Bridge_pattern

The Bridge pattern is going to allow you to possibly have alternative implementations of an algorithm or system.

Though not a classic Bridge pattern example, imagine if you had a few implementations of a data store: one is efficient in space, the other is efficient in raw performance... and you have a business case for offering both in your app or framework.

In terms of your question, "where I can use which pattern," the answer is, wherever it makes sense for your project! Perhaps consider offering a clarification edit to guide the discussion on where you believe you need to use one or the other.

Solution 3 - Design Patterns

Adapter:

  1. It is a structural pattern
  2. It is useful to work with two incompatible interfaces

UML Diagram: from dofactory article:

enter image description here

Target : defines the domain-specific interface that Client uses.

Adapter : adapts the interface Adaptee to the Target interface.

Adaptee : defines an existing interface that needs adapting.

Client : collaborates with objects conforming to the Target interface.

Example:

Square and Rectangle are two different shapes and getting area() of each of them requires different methods. But still Square work on Rectangle interface with conversion of some of the properties.

public class AdapterDemo{
	public static void main(String args[]){
		SquareArea s = new SquareArea(4);
		System.out.println("Square area :"+s.getArea());
	}
}

class RectangleArea {
	public int getArea(int length, int width){
		return length * width;
	}
}

class SquareArea extends RectangleArea {
	
	int length;
	public SquareArea(int length){
		this.length = length;
	}
	public int getArea(){
		return getArea(length,length);
	}
}

Bridge:

  1. It is structural pattern
  2. it decouples an abstraction from its implementation and both can vary independently
  3. It is possible because composition has been used in place of inheritance

EDIT: ( as per @quasoft suggestion)

You have four components in this pattern.

  1. Abstraction: It defines an interface

  2. RefinedAbstraction: It implements abstraction:

  3. Implementor: It defines an interface for implementation

  4. ConcreteImplementor: It implements Implementor interface.

Code snippet:

Gear gear = new ManualGear();
Vehicle vehicle = new Car(gear);
vehicle.addGear();
    
gear = new AutoGear();
vehicle = new Car(gear);
vehicle.addGear();

Related post:

https://stackoverflow.com/questions/319728/when-do-you-use-the-bridge-pattern-how-is-it-different-from-adapter-pattern/37514779#37514779

Key differences: from sourcemaking article

  1. Adapter makes things work after they're designed; Bridge makes them work before they are.
  2. Bridge is designed up-front to let the abstraction and the implementation vary independently. Adapter is retrofitted to make unrelated classes work together.

Solution 4 - Design Patterns

This post has been around for quite a while. However, it is important to understand that a facade is somewhat similar to an adapter but it's not quite the same thing. An adapter "adapts" an existing class to a usually non-compatible client class. Let's say that you have an old workflow system that your application is using as a client. Your company could possibly replace the workflow system with a new "incompatible" one (in terms of interfaces). In most cases, you could use the adapter pattern and write code that actually calls the new workflow engine's interfaces. A bridge is generally used in a different way. If you actually have a system that needs to work with different file systems (i.e. local disk, NFS, etc.) you could use the bridge pattern and create one abstraction layer to work with all your file systems. This would basically be a simple use case for the bridge pattern. The Facade and the adapter do share some properties but facades are usually used to simplify an existing interface/class. In the early days of EJBs there were no local calls for EJBs. Developers always obtained the stub, narrowed it down and called it "pseudo-remotely". This often times caused performance problems (esp. when really called over the wire). Experienced developers would use the facade pattern to provide a very coarse-grained interface to the client. This facade would then in turn do multiple calls to different more fine-grained methods. All in all, this greatly reduced the number of method calls required and increased performance.

Solution 5 - Design Patterns

In the top answer, @James quotes a sentence from the GoF, page 219. I think it's worthwhile reproducing the full explanation here.

> Adapter versus Bridge > The Adapter and Bridge patterns have some common attributes. Both promote flexibility by providing a level of indirection to another object. Both involve forwarding requests to this object from an interface other than its own. > The key difference between these patterns lies in their intents. Adapter focuses on resolving incompatibilities between two existing interfaces. It doesn't focus on how those interfaces are implemented, nor does it consider how they might evolve independently. It's a way of making two independently designed classes work together without reimplementing one or the other. Bridge, on the other hand, bridges an abstraction and its (potentially numerous) implementations. It provides a stable interface to clients even as it lets you vary the classes that implement it. It also accommodates new implementations as the system evolves. > As a result of these differences, Adapter and Bridge are often used at different points in the software lifecycle. An adapter often becomes necessary when you discover that two incompatible classes should work together, generally to avoid replicating code. The coupling is unforeseen. In contrast, the user of a bridge understands up-front that an abstraction must have several implementations, and both may evolve independently. The Adapter pattern makes things work after they're designed; Bridge makes them work before they are. That doesn't mean Adapter is somehow inferior to Bridge; each pattern merely addresses a different problem.

Solution 6 - Design Patterns

Bridge is improved Adapter. Bridge includes adapter and adds additional flexibility to it. Here is how elements from Ravindra's answer map between patterns:

      Adapter  |    Bridge
    -----------|---------------
    Target     | Abstraction
    -----------|---------------
               | RefinedAbstraction
               |
               |   This element is Bridge specific. If there is a group of 
               |   implementations that share the same logic, the logic can be placed here.
               |   For example, all cars split into two large groups: manual and auto. 
               |   So, there will be two RefinedAbstraction classes.
    -----------|--------------- 
    Adapter    | Implementor
    -----------|---------------
    Adaptee    | ConcreteImplementor

Solution 7 - Design Patterns

Looks like shorter and clear answer to me according to another stackoverflow answer here:

  • Adapter is used when you have an abstract interface, and you want to map that interface to another object which has similar functional role, but a different interface.

  • Bridge is very similar to Adapter, but we call it Bridge when you define both the abstract interface and the underlying implementation. I.e. you're not adapting to some legacy or third-party code, you're the designer of all the code but you need to be able to swap out different implementations.

Solution 8 - Design Patterns

Suppose you've a abstract Shape class with a (generic/abstracted) drawing functionality and a Circle who implements the Shape. Bridge pattern simply is a two-way abstraction approach to decouple the implementation ( drawing in Circle ) and generic/abstracted functionality ( drawing in the Shape class ).

What does it really mean? At a first glance, it sounds like a something you already making ( by dependency inversion). So no worries about having a less-ridig or more modular code base. But it's a bit deeper philosophy behind it.

From my understanding, the need of usage pattern might emerge when I need to add new classes which are closely related with the current system ( like RedCircle or GreenCircle ) and which they differ by only a single functionality ( like color ). And I'm gonna need Bridge pattern particularly if the existing system classes ( Circle or Shape ) are to be frequently changed and you don't want newly added classes to be affected from those changes. So that's why the generic drawing functionality is abstracted away into a new interface so that you can alter the drawing behaviour independent from Shape or Circle.

Solution 9 - Design Patterns

There are plenty of answers To distinguish between Adapter and Bridge. But as ppl are looking for code examples, I would give one example for Adapter Design Pattern crafted into a timeline story :

    //---------------------------------------External Vendor/Provider--------------------------------
   
            //Adaptee | RussianTankInterface is adaptee | adaptee lives in is own lala land and do not care about any other class or interface
            RussianTankInterface smerch9K58 = new RussianTank("The Russian Artillery bought by India in October 2015");
				smerch9K58.aboutMyself();
				smerch9K58.stuff();
                smerch9K58.rotate();
                smerch9K58.launch();
		
   
	//---------------------------------2016 : India manufactures Bharat52 ------------------------------ 
	
			//Client_1 :: IndianTank 
            EnemyAttacker bharat52Attacker = new IndianTank("Tank built in India delivered to Army in Jul 2016"); 
   
			// behaves normally -------------------------(1)
				bharat52Attacker.aboutMe();
           		bharat52Attacker.load();
                bharat52Attacker.revolve();
                bharat52Attacker.fireArtillery();
				
    //---------------------------------2019 : India mnufactures Pinaka, and thought about fusion with Russian technology - so adaption required ------------------------------ 
			      
            //Client_2 :: IndianTank 
            EnemyAttacker pinakaAttacker = new IndianTank("Tank built in India in 1998 got upgraded_v1 in 9 Sep 2019"); 
			
			
			
#####----Bilateral-Coalition happens----## 
#####      	India  : I want a fusion artillery technology with 
#####						1) Indian materials and brain-power but
##### 						2) Russian machine-parts-movement technology 
##### 		Russia : Give me your Interface - at max we can help by providing an Adapter 
	
    //---------------------------------------External Vendor/Provider-----------------------------------
	
            //Adapter :: RussianTechnologyAdapter | Russia gets EnemyAttacker interface only from India & creates RussianTechnologyAdapter 
			RussianTechnologyAdapter russianTechnologyAdapter = new RussianTechnologyAdapter(smerch9K58);
           
           
		    //Target | EnemyAttacker was initially ClientInterface but later becomes the Target as story evolves | <- client owns this Interface
			EnemyAttacker dhanushAttacker = russianTechnologyAdapter;
			
#####----Russia keeps her Word----## 
##### 		Russia to India : Here you go! Take Dhanush, a wrapper over our encapsulated adapter, and plug-in anything conforming to your EnemyAttacker.
##### 		India : Thanks a lot!

	//--------------------------------- 2020 : India returns back happily with dhanushAttacker--------------------------------------- 
			
			//Client_2 - adapted behavior -------------------------(2)
				dhanushAttacker.setNavigationCapability(pinakaAttacker.getCuttingEdgeNavigableTargets());
                dhanushAttacker.aboutMe(); //calls RussianInstance -> aboutMyself()
				dhanushAttacker.load();    //calls RussianInstance -> stuff()
                dhanushAttacker.revolve(); //calls RussianInstance -> rotate()
                dhanushAttacker.fireArtillery();  //calls RussianInstance -> launch()
					   
          

Carefully notice :

  • Same API in (1) & (2) behaves differently

  • India can push its brain into wireFrame of Russia e.g dhanushAttacker.setNavigationCapability(pinakaAttacker.get(..))

Noteworthy points

Client side owns:

-  Invoker /Use(uses Adapter later point)/Client
-  ClientInterface (a.k.a Target )

Shared later:

- ClientInterface  ( becomes Target after sharing)

Receiver side owns :

- Adapter (later shared directly or as a wrapper )  
- Adaptee

     

Hoping someone gives an inline for Bridge too :)

Solution 10 - Design Patterns

Bridge is very similar to Adapter, but we call it Bridge when you define both the abstract interface and the underlying implementation, means not adapting to external code, you're the designer of all the code but you need to be able to swap out different implementations.

Solution 11 - Design Patterns

I think it's simple.

The adapter is designed to allow a third party application to work with your application. Conversely, so that your application can work with third party applications.

Using the bridge pattern, it is supposed to connect two or more applications without implementing an adapter.

In fact, a bridge is an interface through which two applications will interact. As an example of bridging, these are PSR interfaces in PHP.

Example:

OtherApp

<?php

interface IRequestDataOtherApp {};
 
interface IResponseDataOtherApp {};
 
class ResponseDataOtherApp implements IResponseDataOtherApp   {

}; 
 
class OtherApp {
    public static function request(IRequestDataOtherApp $requestData):IResponseOtherApp
    {
        // code
        return new ResponseDataOtherApp ();
    }
}

MyApp

<?php 

interface IResponseDataMyApp {};

interface IReqestDataMyApp {};

class ReqestDataMyApp implements IReqestDataMyApp {};

class Adapter {
   
    public static function convertResponseData(IResponseDataOtherApp $response):IResponseDataMyApp 
    {
      
    }
    public static function convertRequestData(IReqestDataMyApp $request):IRequestOtherApp
    {
      
    }
};
$unformattedResponse=OtherApp::request(Adapter::convertRequestData(new ReqestDataMyApp ()));
$myResponse=ResponseAdapter::convertResponseData($unformattedResponse);
//...

In the before example, we have implemented 2 adapters per request and per response. If we rewrite example and try to implement the bridge.

<?php
    interface IBridgeResponse {};

OtherApp

<?php
interface IRequestDataOtherApp {};
interface IResponseDataOtherApp {};
 
class ResponseDataOtherApp  implements IBridgeResponse, IResponseDataOtherApp   {

}; 
 
class OtherApp {
    public static function request(IRequestDataOtherApp $requestData):IResponseOtherApp
    {
        // code
        return new ResponseDataOtherApp  ();
    }
}

MyApp

<?php 

interface IResponseDataMyApp {};

interface IReqestDataMyApp {};

class ReqestDataMyApp implements IReqestDataMyApp {};

class Adapter {

    public static function convertResponseData(IResponseDataOtherApp $response):IResponseDataMyApp 
    {
      
    }

    public static function convertRequestData(IReqestDataMyApp $request):IRequestOtherApp
   {
      
   }
};

$response=OtherApp::request(Adapter::convertRequestData(new ReqestDataMyApp ()));

if($response instanceof IBridgeResponse){
  /** 
The component has implemented IBridgeResponse interface,
thanks to which our application can interact with it.
This is the bridge.

Our application does not have to create an additional adapter
 (if our application can work with IBridgeResponse).
*/
}
//...

In hexagonal architecture, Ports (Interfaces, Contracts) can act as 'Bridges' if you write an application from the very beginning and are ready to accept the rules of another application being used. Otherwise, you will have to write 'Adapters'.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFirozView Question on Stackoverflow
Solution 1 - Design PatternsJamesView Answer on Stackoverflow
Solution 2 - Design PatternsJeff WilcoxView Answer on Stackoverflow
Solution 3 - Design PatternsRavindra babuView Answer on Stackoverflow
Solution 4 - Design PatternsJohn PennerView Answer on Stackoverflow
Solution 5 - Design Patternsjaco0646View Answer on Stackoverflow
Solution 6 - Design Patternspolina-cView Answer on Stackoverflow
Solution 7 - Design PatternsVolodymyrView Answer on Stackoverflow
Solution 8 - Design PatternsstdoutView Answer on Stackoverflow
Solution 9 - Design PatternsArnab DuttaView Answer on Stackoverflow
Solution 10 - Design Patternsprabhat kuberView Answer on Stackoverflow
Solution 11 - Design PatternsAlexeyP0708View Answer on Stackoverflow