|
zip形式
tgz形式
オブジェクト指向についてはまだまだ勉強中ですが、「PHPでGoFのデザインパターンを実装したら、どんな感じになるんだろ?」と思ってしまったので、ちょっとずつやってみることにしました。
間違いやご意見がありましたら、遠慮なくツッコミを入れてくださいm(_"_)m
今回は、Bridgeパターンで「機能と実装の階層を分ける」パターンです(以下のクラス図を参照)。
Abstraction側が機能、Implementor側が実装の各階層になります。Abstraction側は継承により新たなメソッドを追加することで機能拡張を行い、Implementor側はTemplate Methodパターンになっていて、複数の実装を持つことができます。そして、委譲によりそれぞれの階層を結びつけています。このBridgeパターンは、Windows版・Linux版など同じ機能をOS毎に実装しなければならない場合、などに見かけるパターンです。
今回のサンプルは、携帯向け(i-mode版とEZWeb版)の画面を表示する、というもので、表示形式をAbstraction側、表示の実装部分をImplementor側にそれぞれ分けています。
以下がサンプルコードで、動作確認はPHP4.3.0です。ページの先頭にあるリンクから、サンプルスクリプトをダウンロードできます。
●PageDisplay.phl
<?php
class PageDisplay
{
var $impl_;
function PageDisplay($impl)
{
$this->impl_ = $impl;
}
function printContentType()
{
header("Content-Type: " . $this->impl_->getContentType());
}
function printHeader() { $this->impl_->printHeader(); }
function printTitle() { $this->impl_->printTitle(); }
function printData() { $this->impl_->printData(); }
function printFooter() { $this->impl_->printFooter(); }
function printBorder() { $this->impl_->printBorder(); }
function display()
{
$this->printContentType();
$this->printHeader();
$this->printTitle();
$this->printBorder();
$this->printData();
$this->printFooter();
}
}
?>
●MobilePage.phl
<?php
require_once("jp/ne/hi_ho/pat/dimension/Abstract.phl");
?>
<?php
class MobilePage
{
function printContentType() { Abstract::set("open"); }
function printHeader() { Abstract::set("printHeader"); }
function printTitle() { Abstract::set("printTitle"); }
function printData() { Abstract::set("printData"); }
function printFooter() { Abstract::set("printFooter"); }
function printBorder() { Abstract::set("printBorder"); }
}
?>
●ImodePage.phl
<?php
require_once("MobilePage.phl");
?>
<?php
class ImodePage extends MobilePage
{
var $TITLE = "Bridgeパターンのテスト";
function getContentType() { return "text/html"; }
function printHeader()
{
echo "<html><title>" . $this->TITLE . "</title><body>";
}
function printTitle()
{
echo "<center>" . $this->TITLE . "</center>";
}
function printData()
{
echo "何らかのデータです。<br>"
. "何らかのデータです。<br>";
}
function printFooter() { echo "</body></html>"; }
function printBorder() { echo "<hr>"; }
}
?>
●Bridge.php
<?php
<?php
require_once("PageDisplay.phl");
require_once("CopyRightPageDisplay.phl");
require_once("MobilePage.phl");
require_once("ImodePage.phl");
require_once("EzwebPage.phl");
?>
<?php
$pd = new PageDisplay(new ImodePage());
$pd->display();
?>
本来であれば、Abstractionに相当するPageDisplayクラスのコンストラクタで、正しくImplementor型のオブジェクトが渡されたかどうかをチェックする必要がありますが、ちょっと手を抜いてます。。。PHPでは基本的に型がありませんので、こちらにあるようなinstanceOfメソッドを使って実装する感じになるでしょうか?
|