Bridge pattern

Bridge design pattern is the essence of Object Oriented programming best practices. It enforces encapsulation, separation of responsibilities and coding to interfaces. It decouples the classes while maintaining a clear interface between them. Let’s see how it works.

Let’s imagine that we have two types of classes, and we would like them to cooperate, in every possible combination.

For example we can have view classes (web view, mobile view, tablet view, summary view) and resource to display classes (image resource, text resource, audio file resource). Now, instead of creating a class for each combination (web image, mobile image, tablett image, web text, summary text, mobile audio, tablet audio, etc), we use bridge pattern smart design. You can think of it as a bridge between the interfaces, which allows concrete implementations to work together.

Let’s use yet another example to illustrate bridge pattern in java code:

interface LightSource {
	public void turnOn();
	public void turnOff();
}

interface Lamp() {
	public void addLightSource(LightSource);
	public void lightsOn();
	public void lightsOff();
}

public class ColorBulb implements LightSource {
	private final Bulb bulb = new BasicBulb();
	private final Color color;
	public ColorBulb(Color color) { this.color = color; }
	public void turnOn() { bulb.applyFilter(this.color).start(); }
	public void turnOff() { bulb.stop(); }
}

public class LedLight implements LightSource {
	private Led led;
	public LedLight(Led led) { this.led = led; }
	public void turnOn { led.emitLight(); }
	public void turnOff() { led.stopEmitingLight(); }
}

public class DeskLamp implements Lamp {
	private LightSource lightSource;
	public void addLightSource(LightSource lightSource) { this.lightSource = lightSource; }
	public void lightsOn() { if (lightSource!=null) {lightSource.turnOn();} }
	public void lightsOff() { lightSource.turnOff(); }
}

public class PartyLamp implements Lamp {
	private List lightSourcesList = new LinkedList<>();
	public void addLightSource(LightSource lightSource) { lightSourcesList.add(lightSource); }
	public void lightsOn() { lightSourcesList.forEach(l -> l.turnOn())}
	public void lightsOff() { lightSourcesList.forEach(l -> l.turnOff())}
}

As you can see, each light source has its own mechanism for giving light, each lamp is implemented differently, yet they all can interoperate together. Hooray for the bridge pattern!