Meditator パターン | デザインパターン
2022年9年25日
デザインパターン
Meditator
PHP
オライリージャパンによる Head First シリーズ デザインパターン(第2版)第14章 Meditator パターンを、 PHPで書き直してみようという試みです。
Colleague.php
namespace Meditator; abstract class Colleague { abstract public function onEvent(Meditator $meditator) : void; }
Alarm.php
namespace Meditator; class Alarm extends Colleague { public function onEvent(Meditator $meditator) : void { $meditator->doEvent('alarm'); } public function doAlarm() : void { echo 'doAlarm()'; echo "\n"; } }
CoffeePot.php
namespace Meditator; class CoffeePot extends Colleague { public function onEvent(Meditator $meditator) : void { $meditator->doEvent('coffeePot'); } public function doCoffeePot() : void { echo 'doCoffeePot()'; echo "\n"; } }
Calendar.php
namespace Meditator; class Calendar extends Colleague { public function onEvent(Meditator $meditator) : void { $meditator->doEvent('calendar'); } public function doCalendar() : void { echo 'doCalendar()'; echo "\n"; } }
Sprinkler.php
namespace Meditator; class Sprinkler extends Colleague { public function onEvent(Meditator $meditator) : void { $meditator->doEvent('sprinkler'); } public function doSprinkler() : void { echo 'doSprinler()'; echo "\n"; } }
Meditator.php
namespace Meditator; abstract class Meditator { abstract public function doEvent(string $eventType) : void; }
ConcreteMeditator.php
namespace Meditator; class ConcreteMeditator extends Meditator { private Alarm $alarm; private CoffeePot $coffeePot; private Calendar $calendar; private Sprinkler $sprinkler; public function __construct(Alarm $alarm, CoffeePot $coffeePot, Calendar $calendar, Sprinkler $sprinkler) { $this->alarm = $alarm; $this->coffeePot = $coffeePot; $this->calendar = $calendar; $this->sprinkler = $sprinkler; } public function doEvent(string $eventType) : void { switch ($eventType) { case "alarm": self::doAlarmEvent(); break; case "coffeePot": self::doCoffeePotEvent(); break; case "calendar": self::doCalenderEvent(); break; case 'sprinkler': self::doSprinklerEvent(); break; } } public function doAlarmEvent() : void { $this->alarm->doAlarm(); } public function doCoffeePotEvent() : void { $this->coffeePot->doCoffeePot(); } public function doCalenderEvent() : void { $this->calendar->doCalendar(); } public function doSprinklerEvent() : void { $this->sprinkler->doSprinkler(); } }
index.php
use Meditator\Alarm; use Meditator\CoffeePot; use Meditator\Calendar; use Meditator\Sprinkler; use Meditator\ConcreteMeditator; $alarm = new Alarm(); $coffeePot = new CoffeePot(); $calendar = new Calendar(); $sprinkler = new Sprinkler(); $meditator = new ConcreteMeditator($alarm, $coffeePot, $calendar, $sprinkler); $alarm->onEvent($meditator); $coffeePot->onEvent($meditator); $calendar->onEvent($meditator); $sprinkler->onEvent($meditator);
出力結果
doAlarm() doCoffeePot() doCalendar() doSprinler()