Bridge Pattern
Bridge is used when we need to decouple an abstraction from its implementation so that the two can vary independently. This type of design pattern comes under structural pattern as this pattern decouples implementation class and abstract class by providing a bridge structure between them.
This pattern involves an interface which acts as a bridge which makes the functionality of concrete classes independent from interface implementer classes. Both types of classes can be altered structurally without affecting each other.
public interface VehicleAPI { public void createVehicle(int length, int width, int height); }
public class RedCar implements VehicleAPI { @Override public void createVehicle(int length, int width, int height) {
System.out.println("Drawing Car[ color: red, radius: " + radius + ", x: " + x + ", " + y + "]"); } }
public abstract class Vehicle{ protected VehicleAPI vehicleAPI;
protected Vehicle(VehicleAPI vehicleAPI){
this.vehicleAPI= vehicleAPI;
} public abstract void createVehicle();
}
public class Car extends Vehicle{ private int l,w,h; public Car(int l, int w, int h, VehicleAPI vehicleAPI) {
super(vehicleAPI);
this.l= l; this.w = w; this.h= h; } public void draw() { vehicleAPI.createVehicle(l,w,h);
} }
public class Outer {
public void outerPublic() {
}
private void outerPrivate() {
}
class Inner {
public void innerPublic() {
outerPrivate();
}
}
}JVM access rules do not permit private access between nestmates. Ideally, we should get a compilation error for the above example. However, the Java source code compiler permits the access by introducing a level of indirection.
For example, an invocation of a private member is compiled into an invocation of a compiler-generated, package-private, bridging method in the target class, which in turn invokes the intended private method.
This happens behind the scenes. This bridging method slightly increases the size of a deployed application and can confuse users and tools.
Comments
Post a Comment