Bridge パターン | デザインパターン
2022年9年25日
デザインパターン
Bridge
PHP

オライリージャパンによる Head First シリーズ デザインパターン(第2版)第14章 Bridge パターンを、 PHPで書き直してみようという試みです。
RemoteControl.php
namespace Bridge; abstract class RemoteControl { protected TV $tv; public function __construct(TV $tv) { $this->tv = $tv; } public function on() : void { $this->tv->on(); } public function off() : void { $this->tv->off(); } public function setChannel(int $channel) : void { $this->tv->tuneChannel($channel); } }
ConcreteRemote.php
namespace Bridge; class ConcreteRemote extends RemoteControl { public int $currentStation = 8; public function __construct(TV $tv) { parent::__construct($tv); } public function nextChannel() : void { $this->currentStation = $this->currentStation + 1; $this->setChannel($this->currentStation); } public function previousChannel() : void { $this->currentStation = $this->currentStation - 1; $this->setChannel($this->currentStation); } }
TV.php
namespace Bridge; abstract class TV { abstract public function on() : void; abstract public function off() : void; abstract public function tuneChannel(int $channel) : void; }
RCA.php
namespace Bridge; class RCA extends TV { public function on() : void { echo 'RCA製テレビの電源が入りました'; echo "\n"; } public function off() : void { echo 'RCA製テレビの電源が切れました'; echo "\n"; } public function tuneChannel(int $channel) : void { echo 'RCA製テレビのチャンネルは' . strval($channel) . 'です'; echo "\n"; } }
Sony.php
namespace Bridge; class Sony extends TV { public function on() : void { echo 'Sony製テレビの電源が入りました'; echo "\n"; } public function off() : void { echo 'Sony製テレビの電源が切れました'; echo "\n"; } public function tuneChannel(int $channel) : void { echo 'Sony製テレビのチャンネルは' . strval($channel) . 'です'; echo "\n"; } }
index.php
use Bridge\ConcreteRemote; use Bridge\RCA; use Bridge\Sony; $remoteRCA = new ConcreteRemote(new RCA()); $remoteRCA->on(); $remoteRCA->nextChannel(); $remoteRCA->previousChannel(); $remoteRCA->off(); $remoteSony = new ConcreteRemote(new Sony()); $remoteSony->on(); $remoteSony->nextChannel(); $remoteSony->previousChannel(); $remoteSony->off();
出力結果
RCA製テレビの電源が入りました RCA製テレビのチャンネルは9です RCA製テレビのチャンネルは8です RCA製テレビの電源が切れました Sony製テレビの電源が入りました Sony製テレビのチャンネルは9です Sony製テレビのチャンネルは8です Sony製テレビの電源が切れました