PHP デザインパターン(Adapterパターン)


Adapterパターン

↓買ったので、JavaをPHPに読み替えて勉強。そのメモ。

あらかじめ用意されたBannerクラスにアダプタを実装

f:id:taramonera:20101124172311p:image

<?php
/**
 * Adapterパターン 
 */
//あらかじめ用意されたクラス
class Banner{
private $string;
function __construct($string){
$this->string = $string;
}
function showWithParen(){
echo "(".$this->string.")";
}
}
//Bannerに必要とされる機能(インタフェース)
interface MyPrint{
function printWeak();
}
//MyPrintを使ってアダプターとなるPrintBannerを実装
class PrintBanner extends Banner implements MyPrint{
//明示的にコンストラクタを呼び出す(省略可)
function __construct($string){
parent::__construct($string);
}
//インターフェースの実装
function printWeak(){
parent::showWithParen();
}
}
//Print(インタフェース)とPrintBanner(アダプタ)を使うだけで実装できる(Bannerは見えなくてもよい)
$p = new PrintBanner("プリントなう");
$p->printWeak();
?>

あらかじめ用意されたBannerクラスにアダプタを実装(委譲を使った場合)

f:id:taramonera:20101124172329p:image

<?php
/**
 * Adapterパターン(委譲を使ったもの)
 */
//あらかじめ用意されたクラス
class Banner{
private $string;
function __construct($string){
$this->string = $string;
}
function showWithParen(){
echo "(".$this->string.")";
}
}
//Bannerに必要とされる機能(インタフェースではなく抽象クラスを使う)
abstract class MyPrint{
abstract function printWeak();
}
//BannerとPrintのアダプターとなるPrintBanner
//(Bannerクラスは継承できない(2重継承となるため)ので、
//bannerフィールドにBannerクラスのインスタンスを保持してフィールド経由でshowWithParenメソッドを呼び出す)
//委譲
class PrintBanner extends MyPrint{
private $banner;
function __construct($string){
$this->banner = new Banner($string);
}
function printWeak(){
$this->banner->showWithParen();
}
}
$p = new PrintBanner("プリントなう");
$p->printWeak();
?>

Adapterを使うとうれしいこと

すでに存在するプログラム(使用実績がありバグのないもの)を再利用するときに、Adapterパターンが使える。

Adapterパターンで再利用すれば、バグがあった場合でもAdapterのみチェックすればよい。

  • このエントリーをはてなブックマークに追加

コメントをどうぞ

メールアドレスが公開されることはありません。