2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PythonにおけるBridgeパターン:抽象と実装の分離による構造の柔軟性

Posted at

概要

Bridge(ブリッジ)パターンは、
抽象(Abstraction)と実装(Implementation)を分離し、それぞれを独立に拡張可能にする構造パターンである。

機能の階層と実装の階層が直交して増えていくようなケースにおいて、
クラスの組み合わせ爆発を防ぎ、スケーラブルかつ柔軟な構造設計を実現する。


1. なぜBridgeパターンが必要か?

❌ 機能×プラットフォームの直積構造によるクラス爆発

class WindowsDarkButton: ...
class MacOSDarkButton: ...
class WindowsLightButton: ...
class MacOSLightButton: ...

プラットフォームやテーマが増えるたびにクラスの爆発が発生
→ 管理不能で保守性が低下


✅ 機能(抽象)と実装(実体)を分離

button = Button(DarkTheme())

抽象と実装の組み合わせが動的かつ柔軟に構築可能


2. 構造:抽象と実装の分離

✅ 実装インタフェース(Implementor)

class Theme:
    def apply_theme(self):
        raise NotImplementedError

✅ 実装クラス(ConcreteImplementor)

class DarkTheme(Theme):
    def apply_theme(self):
        return "Dark"

class LightTheme(Theme):
    def apply_theme(self):
        return "Light"

✅ 抽象クラス(Abstraction)

class UIComponent:
    def __init__(self, theme: Theme):
        self.theme = theme

    def render(self):
        raise NotImplementedError

✅ 拡張された抽象(Refined Abstraction)

class Button(UIComponent):
    def render(self):
        print(f"Render Button with {self.theme.apply_theme()} theme")

class Modal(UIComponent):
    def render(self):
        print(f"Render Modal with {self.theme.apply_theme()} theme")

✅ 実行例

btn = Button(DarkTheme())
btn.render()  # → Render Button with Dark theme

modal = Modal(LightTheme())
modal.render()  # → Render Modal with Light theme

3. Python的応用:ランタイム差し替えと動的拡張

component = Button(DarkTheme())
component.render()  # → Dark

component.theme = LightTheme()
component.render()  # → Light

実装をランタイムで切り替えられる柔軟さが、Bridgeの強み


4. 実務ユースケース

✅ クロスプラットフォームUI構築

→ OSごとの見た目や振る舞いを抽象化し、共通の機能インタフェースで制御


✅ 通信層のプロトコル切り替え(HTTP, gRPC, WebSocket)

→ APIクライアントの共通インタフェースに対して、プロトコル毎の実装を差し替え可能


✅ ロガー・出力・通知などの柔軟な出力先切り替え

→ ConsoleLogger / FileLogger / RemoteLogger などの実装を、任意の抽象にブリッジ


5. よくある誤用と対策

❌ 抽象と実装の分離が曖昧で、Bridgeが不要な構造になる

→ ✅ 構造が交差(機能×実装)して複雑化する兆候があるかを明確に判断


❌ 実装インタフェースが肥大化しすぎる

→ ✅ Implementor側は用途に応じた小さな責務単位に保つべき


❌ 継承で対応しようとする(サブクラス爆発)

→ ✅ 継承より委譲を優先するのがBridgeの本質


結語

Bridgeパターンとは、“拡張軸を交差可能な形で設計する”ための構造的アプローチである。

  • 機能と実装の交差に対して、疎結合な関係で柔軟な組み合わせを構築
  • 多次元的にスケーラブルな設計を維持しつつ、変化に強いアーキテクチャを実現
  • Pythonのduck typingと委譲を活用することで、より軽量かつ直感的に実装可能

Pythonicとは、“軸を分け、責務を交差可能に設計する”ことであり、
Bridgeパターンはその軸設計に明快さと秩序をもたらす設計技法である。

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?