Monday, November 06, 2006

Bridge Design Pattern

Benefits of Bridge Design Pattern:

1. Share the implementation among the multiple objects
2. Wants to improve extensibility.
3. Wants to share the abstraction and implementation permamantly.
4. Hide the implementation details from client.

What is Bridge Design Pattern :
Bridge pattern decouples the interface from its implementation. Doing this gives the flexibility so that both can vary independently.

Example of Bridge Design Pattern :

The switch is the interface and the actual implementation is the starting of the Television once it’s switched-on. Still, both the switch and the Refrigerator are independent of each other. Another switch can be plugged in for the Refrigerator and this switch can be connected to start Television

package structural.bridge.test;

public interface Switch {

public void switchOn(); //to switch on
public void switchOff(); //to switch off


}

This switch can be implemented by various devices in house, as Television, Refrigerator etc. Here is the sample code for that.

Package structural.bridge.test;

public class Television implements Switch { // implements switch interface

// On position of switch.
public void switchOn() {
System.out.println("Television Switched ON");
}

// Off position of switch.
public void switchOff() {
System.out.println("Television Switched OFF");

}
}


Package structural.bridge.test;

public class Refrigerator implements Switch { // implements switch interface

// On position of switch.
public void switchOn() {
System.out.println("Refrigerator Switched ON");
}

// Off position of switch.
public void switchOff() {
System.out.println("Refrigerator Switched OFF");
}

}

The interface Switch can be implemented in different ways. Switch as an interface as it has only two functions, on and off. But, there may arise a case where some other function be added to it, like change () (change the switch).You need to make the decision earlier to implementation whether the interface should be interface or abstract class.

No comments: