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++ Adapter Pattern 완벽 가이드 | 인터페이스 변환과 호환성
- C++ Decorator Pattern 완벽 가이드 | 기능 동적 추가와 조합
- C++ Proxy Pattern 완벽 가이드 | 접근 제어와 지연 로딩
- C++ Strategy Pattern 완벽 가이드 | 알고리즘 캡슐화와 런타임 교체
이 글에서 다루는 키워드 (관련 검색어)
C++, Bridge, design pattern, structural, abstraction, implementation, renderer, platform 등으로 검색하시면 이 글이 도움이 됩니다.
자주 묻는 질문 (FAQ)
Q. 이 내용을 실무에서 언제 쓰나요?
A. C++ Bridge 패턴 완벽 가이드. 구현(Implementor)과 추상화(Abstraction)를 분리해 플랫폼·드라이버를 바꿔 끼울 수 있게 하는 구조 패턴, 실전 예제, 렌더러 교체, 플랫폼 독립적 설계까지. 실무에서는 위 본문의 예제와 선택 가이드를 참고해 적용하면 됩니다.
Q. 선행으로 읽으면 좋은 글은?
A. 각 글 하단의 이전 글 또는 관련 글 링크를 따라가면 순서대로 배울 수 있습니다. C++ 시리즈 목차에서 전체 흐름을 확인할 수 있습니다.
Q. 더 깊이 공부하려면?
A. cppreference와 해당 라이브러리 공식 문서를 참고하세요. 글 말미의 참고 자료 링크도 활용하면 좋습니다.
관련 글
- C++ Composite 패턴 완벽 가이드 | 트리 구조를 동일 인터페이스로 다루기
- C++ Facade 패턴 완벽 가이드 | 복잡한 서브시스템을 하나의 간단한 인터페이스로
- C++ Flyweight 패턴 완벽 가이드 | 공유로 메모리 절약하기
- C++ 디자인 패턴 | Adapter·Decorator
- 배열과 리스트 | 코딩 테스트 필수 자료구조 완벽 정리