minstudio

브릿지 패턴 (Bridge)

브릿지 패턴(Bridge Pattern)은 추상화(Abstraction)와 구현(Implementation)을 분리하여 두 가지를 독립적으로 확장할 수 있도록 하는 구조 패턴입니다.

리모컨(추상층)과 TV(구현층)를 생각해봅시다. 리모컨의 종류(기본 리모컨, 고급 리모컨)도 다양하게 늘어날 수 있고, TV 브랜드(삼성, LG)도 다양하게 늘어날 수 있습니다. 상속으로만 해결하려면 `SamsungBasicRemote`, `LGAdvancedRemote` 처럼 수많은 클래스가 생성(클래스 폭발)됩니다. 브릿지 패턴은 리모컨 안에 TV 인터페이스를 조립(Composition)시켜 두 계층을 분리하는 다리(Bridge)를 놔줍니다.

🌉 Bridge: 기능(추상)과 구현의 완벽한 분리 Remote (리모컨) protected Device device; BasicRemote AdvancedRemote 위임 (Bridge) << Device >> turnOn(), setVolume() SamsungTV LGTV 클래스 개수: M * N 개에서 M + N 개로 획기적 감소!
<!-- ==========================================
// 📂 Implementation (구현부)
// ==========================================

interface Device {
    void turnOn();
    void setVolume(int percent);
}

class SamsungTV implements Device {
    public void turnOn() { System.out.println("📺 삼성 TV가 켜집니다."); }
    public void setVolume(int p) { System.out.println("삼성 TV 볼륨: " + p); }
}

class LGTV implements Device {
    public void turnOn() { System.out.println("📺 LG TV가 켜집니다."); }
    public void setVolume(int p) { System.out.println("LG TV 볼륨: " + p); }
}

// ==========================================
// 📂 Abstraction (기능부 - 리모컨)
// ==========================================
// 추상 클래스로 정의하고, 내부에 구현 인터페이스(Device)를 포함합니다. (Bridge 역할)
abstract class RemoteControl {
    protected Device device; // 브릿지

    public RemoteControl(Device device) { this.device = device; }
    public abstract void power();
}

class BasicRemote extends RemoteControl {
    public BasicRemote(Device device) { super(device); }

    public void power() {
        System.out.println("리모컨 전원 버튼 누름");
        device.turnOn(); // 구현체로 위임
    }
}

class AdvancedRemote extends RemoteControl {
    public AdvancedRemote(Device device) { super(device); }

    public void power() {
        System.out.println("스마트 리모컨 전원 버튼 누름");
        device.turnOn();
    }
    public void mute() {
        System.out.println("스마트 리모컨 음소거 버튼 누름");
        device.setVolume(0);
    }
}

// ==========================================
// 📂 Main.java (사용 예시)
// ==========================================
public class Main {
    public static void main(String[] args) {
        // 삼성 TV에 일반 리모컨 연결
        Device samsung = new SamsungTV();
        RemoteControl basicRemote = new BasicRemote(samsung);
        basicRemote.power(); 

        // LG TV에 스마트 리모컨 연결 (각자 독립적으로 확장 가능!)
        Device lg = new LGTV();
        AdvancedRemote smartRemote = new AdvancedRemote(lg);
        smartRemote.power();
        smartRemote.mute();
    }
}
브릿지 패턴 (Bridge) | Minstudio