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)を分離し、それぞれ独立に拡張可能にするための構造設計パターンである。

一般的に、継承によって抽象と実装を結びつけると、クラスの組み合わせ数が爆発的に増える
Bridgeパターンはこの問題を避け、構成(Delegation)を用いて柔軟な拡張性と組み合わせの自由度を提供する。


1. なぜBridgeが必要か?

❌ 継承ベースの組み合わせが爆発する構造

- 丸い図形 × 青色
- 丸い図形 × 赤色
- 四角い図形 × 青色
- 四角い図形 × 赤色
...

抽象と実装が固定結合され、拡張性が失われる


✅ 抽象と実装を分離し、構成で結びつける

circle = CircleShape(RedColor())
circle.draw()

自由な組み合わせが可能な構造に


2. 基本構造

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

class Color:
    def paint(self, shape_name):
        raise NotImplementedError

✅ ConcreteImplementor(実際の実装)

class RedColor(Color):
    def paint(self, shape_name):
        print(f"赤色で{shape_name}を描画します。")

class BlueColor(Color):
    def paint(self, shape_name):
        print(f"青色で{shape_name}を描画します。")

✅ Abstraction(抽象部分)

class Shape:
    def __init__(self, color: Color):
        self.color = color

    def draw(self):
        raise NotImplementedError

✅ RefinedAbstraction(具体的な抽象)

class CircleShape(Shape):
    def draw(self):
        self.color.paint("")

class SquareShape(Shape):
    def draw(self):
        self.color.paint("四角")

✅ 使用例

shape1 = CircleShape(RedColor())
shape2 = SquareShape(BlueColor())

shape1.draw()  # → 赤色で円を描画します。
shape2.draw()  # → 青色で四角を描画します。

3. Python的応用:動的インジェクションによるBridge構築

class Logger:
    def log(self, message):
        raise NotImplementedError

class ConsoleLogger(Logger):
    def log(self, message):
        print(f"[Console] {message}")

class FileLogger(Logger):
    def log(self, message):
        with open("log.txt", "a") as f:
            f.write(message + "\n")
class App:
    def __init__(self, logger: Logger):
        self.logger = logger

    def run(self):
        self.logger.log("アプリケーションを起動")

ログ出力先を変更するだけでアプリ本体を変更せずに振る舞いを拡張


4. 実務ユースケース

✅ UIテーマ × コンポーネント(色・動作の分離)

→ ダークテーマ/ライトテーマ × ボタン/スライダーの独立拡張


✅ デバイス × プラットフォーム

→ プリンタ × OS、メディアプレーヤー × 出力形式(HDMI / Bluetooth)


✅ ロガー × 出力先(DB / ファイル / コンソール)

出力先の切り替えによるログ設計の柔軟性向上


✅ データ変換 × 形式(CSV / JSON / XML)

→ 変換ロジックとデータソースの独立管理


5. よくある誤用と対策

❌ 継承で抽象と実装を結びつける設計

→ ✅ 実装はクラス外から構成(Delegation)として注入すべき


❌ 実装クラスが抽象部分に依存している

→ ✅ 依存は一方向(抽象 → 実装)に保つこと


❌ 抽象/実装の責務が曖昧

→ ✅ 抽象は構造と意味、実装は動作と処理の実体に分離すべき


結語

Bridgeパターンとは、“抽象と実装の結合を緩め、拡張性を最大化する設計技法”である。

  • 継承ではなく構成により、機能の組み合わせの自由度と柔軟性を実現
  • 実装と抽象をそれぞれ独立に設計・拡張可能にすることで、将来の変更に強い構造が生まれる
  • Pythonの動的型と依存注入により、直感的かつ強力にBridge構造を組むことができる

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?