Bridge pattern is used to separate the interface from implementation and follows composition instead of inheritance.
Description
Bridge pattern is used when decoupling of interface from implementation should be done. By decoupling, both the interfaces can vary independently. The best example of bridge pattern is "electric bulb". It has two functions-on and off. Bridge Patterns are also known as "handle" or "body".
Advantages
Improves extensibility.
Implementation details can be hidden.
Functional interface and implementation can be linked easily.
Patterns are much flexible.
Implementation changes doesn't effect the pattern.
Conceptual
figure
Abstraction : Abstraction defines the abstraction interface.
AbstractionImpl : Implements the abstraction interface using a reference to an object of type Implementor.
Implementor : Implementor defines the interface for implementation classes. This interface does not need to correspond directly to abstraction interface and can be very different. Abstraction imp provides implementation details in terms of operations provided by the Implementor interface.
ConcreteImplementor1, ConcreteImplementor2 : Implements the Implementor interface.
switch
Examples
Switch has two functions On and Off.
[java]public interface Switch
{
public void switchOn();
public void switchOff();
}[/java]
fan
Examples
Fan can be operated by using switch.
[java]
public class Fan implements Switch
{
public void switchOn()
{
System.out.println("FAN Switched ON");
}
public void switchOff() {
System.out.println("FAN Switched OFF");
}
}[/java]
Electric bulb
Examples
Electric bulb can be operated using switch.
[java]
public class Bulb implements Switch
{
public void switchOn() {
System.out.println("BULB Switched ON");
}
public void switchOff()
{
System.out.println("BULB Switched OFF");
}
}[/java]
Television
Examples
Television can be operated using switch.
[java]
public class Television implements Switch {
public void switchOn()
{
System.out.println("Television Switched ON");
}
public void switchOff()
{
System.out.println(" Television Switched OFF");
}
}[/java]
Washing machine
Examples
Washing machine can be operated using switch.
[java]
public class WashingMachine implements Switch
{
public void switchOn()
{
System.out.println(" WashingMachine switched ON");
}
public void switchOff()
{
System.out.println("WashingMachine Switched OFF");
}
}[/java]
Summary
Key Points
Bridge Pattern are much flexible and can be extended easily without effecting the interface.
It improves the extensibility.
It allows the hiding of implementation details from the client.