デザインパターンを覚えたい (Bridge)
Bridgeパターン
機能と実装を分離させるパターン。機能追加はサブクラスを作成してメソッド追加するとかのことで、実装追加は具象クラスを追加するとかのこと。
この2つの拡張を別々に行えるようにするために、具象クラスの分を公開クラスに集約して扱う。
とりあえず実装。
http://dl.dropbox.com/u/7810000/code/design_pattern/bridge.zip
実行結果。
$ ./bridge_test
### Contact + HogeATM ###
Contact : deposit 1000
Contact : withdraw 3000
Contact : refer
HogeATM : remain credit = 8000### CardContact + FugaATM ###
CardContact : use card[1234] : deposit 3000
Contact : withdraw 10000
Contact : refer
--- history ---
FugaATM : succeed to deposit[3000] : credit[4000]
FugaATM : fail to withdraw[10000] : credit[4000]
---
FugaATM : remain credit[4000]
ポイントはContactクラスの以下の部分。
class Contact { protected: // 実装クラスを集約 ATM* atmImpl; // 処理を実装クラスに移譲する void deposit(int money) { atmImpl->deposit(money); } void withdraw(int money) { atmImpl->withdraw(money); } void refer() { atmImpl->refer(); }
今回の例だと、実際のお金のやり取りを行うATMクラスを外部で宣言して、そのインスタンスをメンバとして持つようにしている。
そのため、ContactクラスではATMに処理をお願いする形で動作する。
サブクラスのCardContactクラスでも同じように動作していて、Contactクラスの機能追加と、ATMクラスの実装追加が切り離されていることがわかる。
Bridgeパターンと似たものとしてAdapterパターンってのがあったけど、
Bridge | 機能追加と実装追加を切り離して扱うためのパターン |
Adapter | 形式の異なるAPI間をつなぐためのパターン |
とそもそも役割が違う。