この記事は検証可能な参考文献や出典が全く示されていないか、不十分です。出典を追加して記事の信頼性向上にご協力ください。(このテンプレートの使い方)
出典検索?: "Adapter パターン"
Adapter パターン(アダプター・パターン)とは、GoF によって定義されたデザインパターンの1つである。Adapter パターンを用いると、既存のクラスに対して修正を加えることなく、インタフェースを変更することができる。Adapter パターンを実現するための手法として継承を利用した手法と委譲を利用した手法が存在する。それぞれについて以下の節で説明する。 継承を利用したAdapterは、利用したいクラスのサブクラスを作成し、そのサブクラスに対して必要なインタフェースを実装することで実現される。 下記の例において、Productクラスは既存のクラスであり修正できないものとする。ここで、Productクラスを利用したい開発者がいて、その開発者はgetPriceというメソッドでProductの値段を取得したいとする。この場合、ProductAdapterというAdapterを作成することで、既存クラス(Product)クラスを修正することなく、異なるインタフェースを持たせることができる。このように、既存クラスを修正することなく、異なるインタフェースを持たせるということが、Adapter パターンの役割である。interface ProductPrice{ public int getPrice();}class Product{ private int cost; public int getCost(){ return cost; }}class ProductAdapter extends Product implements ProductPrice{ public int getPrice(){ return this.getCost(); }} 継承を利用したAdapterのクラス図は以下のようになる。Adapter は Adaptee を継承し、同時に Target を実装する。実装したメソッド Adapter#requiredMethod() 内で Adaptee#oldMethod() を実行する 参考までに、上のサンプルコードとこのクラス図との対応を示す。 委譲を利用したAdapterは、利用したいクラスのインスタンスを生成し、そのインスタンスを他クラスから利用することで実現される。 委譲を利用したAdapterのクラス図は以下のようになる。Adapter は Adaptee をメンバに持ち、同時に Target を実装する。実装したメソッド Adapter#requiredMethod() 内で、メンバの Adaptee#oldMethod() を実行する ※上図において、extendsはimplementsでも良い。 こちらのほうも、参考までにサンプルコードの対応を示す。 生成に関するパターン
継承を利用したAdapter
サンプルプログラム
クラス図
Target
ProductPrice
Target#requiredMethod
ProductPrice#getPrice()
Adapter
ProductAdapter
Adapter#requiredMethod
ProductAdapter#getPrice()
Adaptee
Product
Adaptee#oldMethod
Product#getCost()
委譲を利用したAdapter
サンプルプログラムinterface ProductPrice{ public int getPrice();}class Product{ private int cost; public int getCost(){ return cost; }}class ProductAdapter implements ProductPrice{ private Product product = new Product(); public int getPrice(){ return product.getCost(); }}
クラス図
Target
ProductPrice
Target#requiredMethod()
ProductPrice#getPrice()
Adapter
ProductAdapter
Adapter#requiredMethod()
ProductAdapter#getPrice()
Adaptee
Product
Adaptee#oldMethod()
Product#getCost()
表
話
編
歴
デザインパターン
GoFによる23種のパターン
Abstract factory
Builder
Factory method
Prototype
Singleton
構造に関するパターン
Adapter
Bridge
Composite
Decorator
Facade
Flyweight
Proxy
振る舞いに関するパターン
Chain of responsibility
Command
Interpreter
Iterator
Mediator
Memento
Observer
State
Strategy
Template method
Visitor
並行性に関するパターン
Active object
Balking(英語版)
Double-checked locking(英語版)
Event-based asynchronous(英語版)
Guarded suspension(英語版)
Join(英語版)
ロック
モニタ
Proactor(英語版)
Reactor
Readers?writer lock(英語版)
Scheduler(英語版)
Thread pool(英語版)
スレッド局所記憶
アーキテクチャに関するパターン
Front Controller(英語版)
Interceptor(英語版)
MVC
MVVM
多層アーキテクチャ
Specification(英語版)
出版-購読型モデル
Naked objects(英語版)
Service Locator(英語版)
Active Record
Identity map(英語版)
Data Access Object
Data Transfer Object
その他のパターン
依存性の注入 (DI)
遅延読み込み
モックオブジェクト