What is the difference between the Bridge and Adapter 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
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.
Adapter:
UML Diagram: from dofactory article:
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:
EDIT: ( as per @quasoft suggestion)
You have four components in this pattern.
Abstraction: It defines an interface
RefinedAbstraction: It implements abstraction:
Implementor: It defines an interface for implementation
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:
When do you use the Bridge Pattern? How is it different from Adapter pattern?
Key differences: from sourcemaking article