본문으로 건너뛰기
Previous
Next
C++ Bridge 패턴 완벽 가이드 | 구현과 추상화 분리로 확장성 높이기

C++ Bridge 패턴 완벽 가이드 | 구현과 추상화 분리로 확장성 높이기

C++ Bridge 패턴 완벽 가이드 | 구현과 추상화 분리로 확장성 높이기

이 글의 핵심

C++ Bridge 패턴 구현(Implementor)과 추상화(Abstraction)를 분리해 플랫폼·드라이버를 바꿔 끼울 수 있게 하는 구조 패턴, 실전 예제, 렌더러 교체, 플랫폼 독립적 설계까지.

Bridge 패턴이란? 왜 필요한가

구조 패턴 시리즈에서 Adapter·Composite 등과 나란히 보면 “추상과 구현 분리”가 어디에 해당하는지 구분하기 쉽습니다.

문제 시나리오: 조합 폭발

문제: Shape(원, 사각형)와 Renderer(OpenGL, Vulkan)를 상속으로 조합하면 클래스가 폭발합니다.

// 나쁜 설계: 조합 폭발
class OpenGLCircle : public Shape { };
class VulkanCircle : public Shape { };
class OpenGLRectangle : public Shape { };
class VulkanRectangle : public Shape { };
// Shape 3개 × Renderer 2개 = 6개 클래스
// Color 추가 시 3 × 2 × 3 = 18개...

해결: Bridge 패턴추상화(Shape)와 구현(Renderer)을 분리합니다. Shape는 Renderer를 참조만 하고, 둘을 독립적으로 확장할 수 있습니다.

// 좋은 설계: Bridge
// 타입 정의
class Shape {
protected:
    std::shared_ptr<Renderer> renderer_;
public:
    explicit Shape(std::shared_ptr<Renderer> r) : renderer_(std::move(r)) {}
    virtual void draw() = 0;
};
class Circle : public Shape {
    void draw() override { renderer_->drawCircle(...); }
};
// Shape 추가 시 1개 클래스만, Renderer 추가 시 1개 클래스만
flowchart LR
    client[Client]
    abstraction[Abstractionbr/(Shape)]
    implementor[Implementorbr/(Renderer)]
    refined["RefinedAbstractionbr/(Circle, Rectangle)"]
    concrete["ConcreteImplementorbr/(OpenGLRenderer, VulkanRenderer)"]
    
    client --> abstraction
    abstraction --> implementor
    refined -.extends.-> abstraction
    concrete -.implements.-> implementor

1. 기본 구조

#include <memory>
#include <iostream>
// 구현부 인터페이스 (Implementor)
class Renderer {
public:
    virtual void drawCircle(float x, float y, float r) = 0;
    virtual void drawRect(float x, float y, float w, float h) = 0;
    virtual ~Renderer() = default;
};
// 구체적 구현 1
class OpenGLRenderer : public Renderer {
public:
    void drawCircle(float x, float y, float r) override {
        std::cout << "[OpenGL] Circle at (" << x << "," << y << ") r=" << r << '\n';
    }
    void drawRect(float x, float y, float w, float h) override {
        std::cout << "[OpenGL] Rect at (" << x << "," << y << ") " << w << "x" << h << '\n';
    }
};
// 구체적 구현 2
class VulkanRenderer : public Renderer {
public:
    void drawCircle(float x, float y, float r) override {
        std::cout << "[Vulkan] Circle at (" << x << "," << y << ") r=" << r << '\n';
    }
    void drawRect(float x, float y, float w, float h) override {
        std::cout << "[Vulkan] Rect at (" << x << "," << y << ") " << w << "x" << h << '\n';
    }
};
// 추상화부 (Abstraction) — 구현을 참조
class Shape {
protected:
    std::shared_ptr<Renderer> renderer_;
public:
    explicit Shape(std::shared_ptr<Renderer> r) : renderer_(std::move(r)) {}
    virtual void draw() = 0;
    virtual ~Shape() = default;
};
class Circle : public Shape {
    float x_, y_, r_;
public:
    Circle(std::shared_ptr<Renderer> r, float x, float y, float radius)
        : Shape(std::move(r)), x_(x), y_(y), r_(radius) {}
    void draw() override { renderer_->drawCircle(x_, y_, r_); }
};
class Rectangle : public Shape {
    float x_, y_, w_, h_;
public:
    Rectangle(std::shared_ptr<Renderer> r, float x, float y, float w, float h)
        : Shape(std::move(r)), x_(x), y_(y), w_(w), h_(h) {}
    void draw() override { renderer_->drawRect(x_, y_, w_, h_); }
};
int main() {
    auto gl = std::make_shared<OpenGLRenderer>();
    auto vk = std::make_shared<VulkanRenderer>();
    
    Circle c1(gl, 0, 0, 10);
    Circle c2(vk, 5, 5, 3);
    Rectangle r1(gl, 10, 10, 50, 30);
    
    c1.draw();  // [OpenGL] Circle
    c2.draw();  // [Vulkan] Circle
    r1.draw();  // [OpenGL] Rect
    return 0;
}

2. 렌더러 교체 예제

런타임에 렌더러 변경

#include <memory>
#include <iostream>
class Renderer {
public:
    virtual void render(const std::string& content) = 0;
    virtual ~Renderer() = default;
};
class HTMLRenderer : public Renderer {
public:
    void render(const std::string& content) override {
        std::cout << "<html><body>" << content << "</body></html>\n";
    }
};
class MarkdownRenderer : public Renderer {
public:
    void render(const std::string& content) override {
        std::cout << "# " << content << "\n";
    }
};
class Document {
protected:
    std::shared_ptr<Renderer> renderer_;
    std::string content_;
public:
    Document(std::shared_ptr<Renderer> r, std::string content)
        : renderer_(std::move(r)), content_(std::move(content)) {}
    
    void setRenderer(std::shared_ptr<Renderer> r) {
        renderer_ = std::move(r);
    }
    
    virtual void display() = 0;
    virtual ~Document() = default;
};
class Article : public Document {
public:
    using Document::Document;
    
    void display() override {
        std::cout << "=== Article ===\n";
        renderer_->render(content_);
    }
};
int main() {
    auto html = std::make_shared<HTMLRenderer>();
    auto md = std::make_shared<MarkdownRenderer>();
    
    Article article(html, "Hello World");
    article.display();  // HTML 렌더링
    
    article.setRenderer(md);
    article.display();  // Markdown 렌더링
    return 0;
}

핵심: 런타임에 setRenderer()로 구현을 교체할 수 있습니다.

3. 플랫폼 독립적 설계

크로스 플랫폼 파일 시스템

#include <memory>
#include <iostream>
#include <string>
// 구현부: 플랫폼별 파일 연산
class FileSystemImpl {
public:
    virtual bool exists(const std::string& path) = 0;
    virtual std::string read(const std::string& path) = 0;
    virtual void write(const std::string& path, const std::string& data) = 0;
    virtual ~FileSystemImpl() = default;
};
class WindowsFileSystem : public FileSystemImpl {
public:
    bool exists(const std::string& path) override {
        std::cout << "[Windows] Checking: " << path << '\n';
        return true;
    }
    std::string read(const std::string& path) override {
        return "[Windows] File content";
    }
    void write(const std::string& path, const std::string& data) override {
        std::cout << "[Windows] Writing to " << path << '\n';
    }
};
class LinuxFileSystem : public FileSystemImpl {
public:
    bool exists(const std::string& path) override {
        std::cout << "[Linux] Checking: " << path << '\n';
        return true;
    }
    std::string read(const std::string& path) override {
        return "[Linux] File content";
    }
    void write(const std::string& path, const std::string& data) override {
        std::cout << "[Linux] Writing to " << path << '\n';
    }
};
// 추상화부: 플랫폼 독립적 API
class File {
protected:
    std::shared_ptr<FileSystemImpl> fs_;
    std::string path_;
public:
    File(std::shared_ptr<FileSystemImpl> fs, std::string path)
        : fs_(std::move(fs)), path_(std::move(path)) {}
    
    bool exists() { return fs_->exists(path_); }
    std::string read() { return fs_->read(path_); }
    void write(const std::string& data) { fs_->write(path_, data); }
};
class ConfigFile : public File {
public:
    using File::File;
    
    void load() {
        if (exists()) {
            std::cout << "Config loaded: " << read() << '\n';
        }
    }
};
int main() {
#ifdef _WIN32
    auto fs = std::make_shared<WindowsFileSystem>();
#else
    auto fs = std::make_shared<LinuxFileSystem>();
#endif
    
    ConfigFile config(fs, "/etc/app.conf");
    config.load();
    return 0;
}

핵심: 컴파일 타임에 플랫폼 구현을 선택하고, 추상화 계층은 동일한 API를 제공합니다.

4. 자주 발생하는 문제와 해결법

문제 1: 순환 의존성

// ❌ 나쁜 예: Renderer가 Shape를 참조
class Renderer {
    std::vector<Shape*> shapes_;  // 순환 의존!
};

해결: 구현부(Implementor)는 추상화부(Abstraction)를 알면 안 됩니다. 단방향 의존만 유지하세요.

// ✅ 좋은 예: Shape만 Renderer를 참조
class Shape {
    std::shared_ptr<Renderer> renderer_;  // 단방향
};

문제 2: 구현 누수

// ❌ 나쁜 예: 추상화가 구체 타입에 의존
class Circle : public Shape {
    OpenGLRenderer* gl_;  // 구체 타입!
};

해결: 추상화는 Implementor 인터페이스만 알아야 합니다.

// ✅ 좋은 예
class Circle : public Shape {
    std::shared_ptr<Renderer> renderer_;  // 인터페이스만
};

문제 3: 불필요한 Bridge

간단한 경우 Bridge는 과도합니다.

// ❌ 과도한 설계: 구현이 1개뿐
class Logger {
    std::shared_ptr<LoggerImpl> impl_;  // 불필요
};

해결: 구현이 2개 이상 필요하거나, 플랫폼/드라이버 교체가 예상될 때만 Bridge를 쓰세요.

5. 프로덕션 패턴

패턴 1: 팩토리와 조합

class RendererFactory {
public:
    static std::shared_ptr<Renderer> create(const std::string& type) {
        if (type == "opengl") return std::make_shared<OpenGLRenderer>();
        if (type == "vulkan") return std::make_shared<VulkanRenderer>();
        return nullptr;
    }
};
int main() {
    auto renderer = RendererFactory::create("opengl");
    Circle c(renderer, 0, 0, 10);
    c.draw();
}

패턴 2: 의존성 주입

class Application {
    std::shared_ptr<Renderer> renderer_;
public:
    Application(std::shared_ptr<Renderer> r) : renderer_(std::move(r)) {}
    
    void run() {
        Circle c(renderer_, 0, 0, 10);
        c.draw();
    }
};
int main() {
    auto renderer = std::make_shared<OpenGLRenderer>();
    Application app(renderer);  // DI
    app.run();
}

6. 완전한 예제: 크로스 플랫폼 윈도우 시스템

#include <memory>
#include <iostream>
#include <string>
// 구현부: 플랫폼별 윈도우 생성
class WindowImpl {
public:
    virtual void createWindow(const std::string& title, int w, int h) = 0;
    virtual void show() = 0;
    virtual void hide() = 0;
    virtual ~WindowImpl() = default;
};
class Win32Window : public WindowImpl {
    std::string title_;
public:
    void createWindow(const std::string& title, int w, int h) override {
        title_ = title;
        std::cout << "[Win32] CreateWindow: " << title << " " << w << "x" << h << '\n';
    }
    void show() override { std::cout << "[Win32] ShowWindow: " << title_ << '\n'; }
    void hide() override { std::cout << "[Win32] HideWindow: " << title_ << '\n'; }
};
class X11Window : public WindowImpl {
    std::string title_;
public:
    void createWindow(const std::string& title, int w, int h) override {
        title_ = title;
        std::cout << "[X11] XCreateWindow: " << title << " " << w << "x" << h << '\n';
    }
    void show() override { std::cout << "[X11] XMapWindow: " << title_ << '\n'; }
    void hide() override { std::cout << "[X11] XUnmapWindow: " << title_ << '\n'; }
};
// 추상화부: 플랫폼 독립적 Window API
class Window {
protected:
    std::shared_ptr<WindowImpl> impl_;
    std::string title_;
    int width_, height_;
public:
    Window(std::shared_ptr<WindowImpl> impl, std::string title, int w, int h)
        : impl_(std::move(impl)), title_(std::move(title)), width_(w), height_(h) {
        impl_->createWindow(title_, width_, height_);
    }
    
    virtual void open() { impl_->show(); }
    virtual void close() { impl_->hide(); }
    virtual ~Window() = default;
};
class DialogWindow : public Window {
public:
    using Window::Window;
    
    void open() override {
        std::cout << "Opening dialog...\n";
        Window::open();
    }
};
class MainWindow : public Window {
public:
    using Window::Window;
    
    void open() override {
        std::cout << "Opening main window...\n";
        Window::open();
    }
};
int main() {
#ifdef _WIN32
    auto impl = std::make_shared<Win32Window>();
#else
    auto impl = std::make_shared<X11Window>();
#endif
    
    MainWindow mainWin(impl, "My App", 800, 600);
    mainWin.open();
    
    DialogWindow dialog(impl, "Settings", 400, 300);
    dialog.open();
    dialog.close();
    
    return 0;
}

출력 (Windows):

[Win32] CreateWindow: My App 800x600
Opening main window...
[Win32] ShowWindow: My App
[Win32] CreateWindow: Settings 400x300
Opening dialog...
[Win32] ShowWindow: Settings
[Win32] HideWindow: Settings

정리

항목설명
목적추상화와 구현을 분리해 둘을 독립적으로 확장
장점플랫폼·드라이버 교체 용이, 상속 조합 폭발 방지, 런타임 구현 교체 가능
단점클래스 수 증가, 설계 복잡도, 간단한 경우 과도할 수 있음
사용 시기플랫폼/렌더러/드라이버가 2개 이상, 런타임 교체 필요, 조합 폭발 방지
관련 글: Adapter 패턴, Decorator 패턴, Proxy 패턴, Strategy 패턴, Facade 패턴.
한 줄 요약: Bridge 패턴으로 렌더러·플랫폼·드라이버를 독립적으로 확장하고 런타임에 교체할 수 있습니다.

같이 보면 좋은 글 (내부 링크)

이 주제와 연결되는 다른 글입니다.


이 글에서 다루는 키워드 (관련 검색어)

C++, Bridge, design pattern, structural, abstraction, implementation, renderer, platform 등으로 검색하시면 이 글이 도움이 됩니다.

자주 묻는 질문 (FAQ)

Q. 이 내용을 실무에서 언제 쓰나요?

A. C++ Bridge 패턴 완벽 가이드. 구현(Implementor)과 추상화(Abstraction)를 분리해 플랫폼·드라이버를 바꿔 끼울 수 있게 하는 구조 패턴, 실전 예제, 렌더러 교체, 플랫폼 독립적 설계까지. 실무에서는 위 본문의 예제와 선택 가이드를 참고해 적용하면 됩니다.

Q. 선행으로 읽으면 좋은 글은?

A. 각 글 하단의 이전 글 또는 관련 글 링크를 따라가면 순서대로 배울 수 있습니다. C++ 시리즈 목차에서 전체 흐름을 확인할 수 있습니다.

Q. 더 깊이 공부하려면?

A. cppreference와 해당 라이브러리 공식 문서를 참고하세요. 글 말미의 참고 자료 링크도 활용하면 좋습니다.

관련 글

심화 부록: 구현·운영 관점

이 부록은 앞선 본문에서 다룬 주제(「C++ Bridge 패턴 완벽 가이드 | 구현과 추상화 분리로 확장성 높이기」)를 구현·런타임·운영 관점에서 다시 압축합니다. 도메인별 세부 구현은 글마다 다르지만, 입력 검증 → 핵심 연산 → 부작용(I/O·네트워크·동시성) → 관측의 흐름으로 장애를 나누면 원인 추적이 빨라집니다.

내부 동작과 핵심 메커니즘

flowchart TD
  A[입력·요청·이벤트] --> B[파싱·검증·디코딩]
  B --> C[핵심 연산·상태 전이]
  C --> D[부작용: I/O·네트워크·동시성]
  D --> E[결과·관측·저장]
sequenceDiagram
  participant C as 클라이언트/호출자
  participant B as 경계(런타임·게이트웨이·프로세스)
  participant D as 의존성(API·DB·큐·파일)
  C->>B: 요청/이벤트
  B->>D: 조회·쓰기·RPC
  D-->>B: 지연·부분 실패·재시도 가능
  B-->>C: 응답 또는 오류(코드·상관 ID)
  • 불변 조건(Invariant): 버퍼 경계, 프로토콜 상태, 트랜잭션 격리, FD 상한 등 단계별로 문장으로 적어 두면 디버깅 비용이 줄어듭니다.
  • 결정성: 순수 층과 시간·네트워크·스케줄에 의존하는 층을 분리해야 테스트와 장애 분석이 쉬워집니다.
  • 경계 비용: 직렬화, 인코딩, syscall 횟수, 락 경합, 할당·GC, 캐시 미스를 의심 목록에 둡니다.
  • 백프레셔: 생산자가 소비자보다 빠를 때 버퍼·큐·스트림에서 속도를 줄이는 신호를 어디에 둘지 정의합니다.

프로덕션 운영 패턴

영역운영 관점 질문
관측성요청 단위 상관 ID, 에러율·지연 p95/p99, 의존성 타임아웃·재시도가 대시보드에 보이는가
안전성입력 검증·권한·비밀·감사 로그가 코드 경로마다 일관적인가
신뢰성재시도는 멱등 연산에만 적용되는가, 서킷 브레이커·백오프·DLQ가 있는가
성능캐시·배치 크기·커넥션 풀·인덱스·백프레셔가 데이터 규모에 맞는가
배포롤백 룬북, 카나리/블루그린, 마이그레이션·피처 플래그가 문서화되어 있는가
용량피크 트래픽·디스크·FD·스레드 풀 상한을 주기적으로 검증하는가

스테이징은 데이터 양·네트워크 RTT·동시성을 프로덕션에 가깝게 맞출수록 재현율이 올라갑니다.

확장 예시: 엔드투엔드 미니 시나리오

앞선 본문 주제(「C++ Bridge 패턴 완벽 가이드 | 구현과 추상화 분리로 확장성 높이기」)를 배포·운영 흐름에 맞춰 옮긴 체크리스트입니다. 도메인에 맞게 단계 이름만 바꿔 적용할 수 있습니다.

  1. 입력 계약 고정: 스키마·버전·최대 페이로드·타임아웃·에러 코드를 경계에 둔다.
  2. 핵심 경로 계측: 요청 ID, 단계별 지연, 외부 호출 결과 코드를 로그·메트릭·트레이스에서 한 흐름으로 본다.
  3. 실패 주입: 의존성 타임아웃·5xx·부분 데이터·락 대기를 스테이징에서 재현한다.
  4. 호환·롤백: 설정/마이그레이션/클라이언트 버전을 되돌릴 수 있는지 확인한다.
  5. 부하 후 검증: 피크 대비 p95/p99, 에러율, 리소스 상한, 알림 임계값을 점검한다.
handle(request):
  ctx = newCorrelationId()
  validated = validateSchema(request)
  authorize(validated, ctx)
  result = domainCore(validated)
  persistOrEmit(result, idempotentKey)
  recordMetrics(ctx, latency, outcome)
  return result

문제 해결(Troubleshooting)

증상가능 원인조치
간헐적 실패레이스, 타임아웃, 외부 의존성, DNS최소 재현 스크립트, 분산 트레이스·로그 상관관계, 재시도·서킷 설정 점검
성능 저하N+1, 동기 I/O, 락 경합, 과도한 직렬화, 캐시 미스프로파일러·APM으로 핫스팟 확인 후 한 가지씩 제거
메모리 증가캐시 무제한, 구독/리스너 누수, 대용량 버퍼, 커넥션 미반납상한·TTL·힙/FD 스냅샷 비교
빌드·배포만 실패환경 변수, 권한, 플랫폼 차이, lockfileCI 로그와 로컬 diff, 런타임·이미지 버전 핀
설정 불일치프로필·시크릿·기본값, 리전스키마 검증된 설정 단일 소스와 배포 매트릭스 표준화
데이터 불일치비멱등 재시도, 부분 쓰기, 캐시 무효화 누락멱등 키·아웃박스·트랜잭션 경계 재검토

권장 순서: (1) 최소 재현 (2) 최근 변경 범위 축소 (3) 환경·의존성 차이 (4) 관측으로 가설 검증 (5) 수정 후 회귀·부하 테스트.

배포 전에는 git addgit commitgit pushnpm run deploy 순서를 권장합니다.