デザインパターンから学ぶオブジェクト指向 【02. Adapter】
デザインパターン記事まとめ
01. Iterator 02. Adapter (ここ)
02. Adapter
今回は Adapterパターン 。
これも利用頻度高そう?
やっぱり、手を動かすと頭が整理される。
実装したコード
継承を利用したAdapterパターン
<?php interface Aisatsu // 挨拶インターフェース { public function aisatsu(); // 挨拶メソッド } class Japan implements Aisatsu { public function aisatsu() { echo "Ohayou!!\n"; } } class English { public function greeting() { echo "Good morning!!\n"; } } class EnglishAdapter extends English implements Aisatsu { public function aisatsu() { $this->greeting(); } } class Worker { public function output($language) { $language->aisatsu(); } } $worker = new Worker(); $jp = new Japan(); $worker->output($jp); $en = new EnglishAdapter(); $worker->output($en);
委譲を利用したAdapterパターン
<?php interface Aisatsu // 挨拶インターフェース { public function aisatsu(); // 挨拶メソッド } class Japan implements Aisatsu { public function aisatsu() { echo "Ohayou!!\n"; } } class English { public function greeting() { echo "Good morning!!\n"; } } class EnglishAdapter implements Aisatsu { private $en; public function aisatsu() { $en = new English(); $en->greeting(); } } class Worker { public function output($language) { $language->aisatsu(); } } $worker = new Worker(); $jp = new Japan(); $worker->output($jp); $en = new EnglishAdapter(); $worker->output($en);