Bridge Design Pattern in Java

Bridge splits a class into two parts, what it is and how it works, so both can change on their own.

Real life example

A remote control (abstraction) works with any device: TV, radio, etc. (implementation).

When to use

You have two things that can vary, like 3 remotes x 4 devices, and you do not want 12 classes.

Complete Java example

Save this as Main.java, then run javac Main.java and java Main.

public class Main {
    public static void main(String[] args) {
        new BasicRemote(new Tv()).press();                 // TV on
        new BasicRemote(new Radio()).press();              // Radio on
    }
}

interface Device { void on(); }
class Tv    implements Device { public void on() { System.out.println("TV on"); } }
class Radio implements Device { public void on() { System.out.println("Radio on"); } }

abstract class Remote {
    protected Device device;                       // this is the "bridge"
    Remote(Device d) { device = d; }
    abstract void press();
}
class BasicRemote extends Remote {
    BasicRemote(Device d) { super(d); }
    void press() { device.on(); }
}

Output

TV on
Radio on