The Bridge Pattern is used to separate out the interface from its implementation. Doing this gives the flexibility so that both can vary independently.
The best example for this is like the electric equipments you have at home and their switches. For e.g., the switch of the fan. The switch is the interface and the actual implementation is the Running of the fan once its switched-on. Still, both the switch and the fan are independent of each other. Another switch can be plugged in for the fan and this switch can be connected to light bulb.
Let’s see how we can convert this into a software program. Switch is the interface having two functions, switchOn() and switchOff().
Here is the sample code for Switch.
Switch.java
package structural.bridge; /** * Just two methods. on and off. */ public interface Switch { | ||
// Two positions of switch. public void switchOn(); public void switchOff(); | ||
}// End of interface |
Fan.java
package structural.bridge; /** * 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"); } | ||
}// End of class |
And implementation as Bulb.
Bulb.java
package structural.bridge; /** * Implement the switch for Fan */ 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"); } | ||
}// End of class |
Here, we can see, that the interface Switch can be implemented in different ways. Here, we can easily use 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). In this case, the interface will change and so, the implementations will also changed, for such cases, you should use the Switch as abstract class. This decision should be made earlier to implementation whether the interface should be interface or abstract class.
No comments:
Post a Comment