Core Java Design Pattern : Structural Pattern : Bridge Design Pattern
Bridge Design Pattern |
Decouple an abstraction from its implementation so that the two can vary independently.
Also Known As :Handle/Body
Use the Bridge pattern when
- you want to avoid a permanent binding between an abstraction and its implementation. This might be the case, for example, when the implementation must be selected or switched at run-time.
- both the abstractions and their implementations should be extensible by subclassing. In this case, the Bridge pattern lets you combine the different abstractions and implementations and extend them independently.
- changes in the implementation of an abstraction should have no impact on clients; that is, their code should not have to be recompiled.
The Bridge pattern decouples an abstraction from its implementation, so that the two can vary independently. A household switch controlling lights, ceiling fans, etc. is an example of the Bridge. The purpose of the switch is to turn a device on or off.
Examples |
Switch.java
package com.javaskool;
// Interface with two methods - on and off.
public interface Switch {
// Two positions of switch.
public void switchOn();
public void switchOff();
}
//This switch can be implemented by various
//devices in house, as Fan, Light Bulb etc.
//Here is the sample code for that.
Fan.java
package com.javaskool;
//Implement the switch for Fan
public class Fan implements Switch {
// Two positions of switch.
public void switchOn() {
System.out.println("FAN Switched ON");
}
public void switchOff() {
System.out.println("FAN Switched OFF");
}
}
Bulb.java
package com.javaskool;
//Implement the switch for Bulb
public class Bulb implements Switch {
// Two positions of switch.
public void switchOn() {
System.out.println("BULB Switched ON");
}
public void switchOff() {
System.out.println("BULB Switched OFF");
}
}
TestDrive.java
package com.javaskool;
public class TestDrive {
public static void main(String[] args) {
Switch phillips=new Fan();//bridge between switch and fan
phillips.switchOn();
phillips.switchOff();
phillips=new Bulb();//bridge between switch and bulb
phillips.switchOn();
phillips.switchOff();
}
}
Output
c:\>javac -d . *.java
c:\>java com.javaskool.TestDrive
FAN Switched ON
FAN Switched OFF
BULB Switched ON
BULB Switched OFF
Recent Comments