The Chain of Responsibility
Let's create a PHP example:
The first thing I want to do is to create is the interface Handler. We add the two method definitions:
public function setNext(Handler $handler): Handler; public function handle(string $request): ?string;The method stub setNext Next we create a class called AbstractHandler it implements Handler and missing methods setNext and handle
we add code to setNext and to this interpase
$this->nextHandler = $handler; return $handler;and
if ($this->nextHandler) {
return $this->nextHandler->handle($request);
}
return null;
we next add the class SquirrelHandler which extends AbstractHandler to it we add:
public function handle(string $request): ?string
{
if ($request === "Nut") {
return "Squirrel: I'll eat the " . $request . ".
";
} else {
return parent::handle($request);
}
}
let's add another anamale DogHandler
public function handle(string $request): ?string
{
if ($request === "MeatBall") {
return "Dog: I'll eat the " . $request . ".\n";
} else {
return parent::handle($request);
}
}
lastly we add the class MouseHandler and have it extends AbstractHandler and we add the code:
public function handle(string $request): ?string
{
if ($request === "Cheese") {
return "Mouse: I'll eat the " . $request . ".
";
} else {
return parent::handle($request);
}
}
for our demo we go to the index.php file and add sime includes:
include_once ('Handler.php');
include_once ('AbstractHandler.php');
and we also need to add the folloing includes:
include_once('MouseHandler.php');
include_once ('SquirrelHandler.php');
include_once ('DogHandler.php');
now to the file we add the client function:
function clientCode(Handler $handler)
{
foreach (["Nut", "Cheese", "Cup of coffee"] as $food) {
echo "Client: Who wants the " . $food . "?
";
$result = $handler->handle($food);
if ($result) {
echo " " . $result;
} else {
echo " " . $food . " was left untouched.";
}
}
}
next we define the following local varables:
$mouse = new MouseHandler; $squirrel = new SquirrelHandler; $dog = new DogHandler;next we consider the following code to demo the chain of responsibity
$mouse->setNext($squirrel)->setNext($dog); echo "Chain: Mouse > Squirrel > Dogthanks for being a part of The Ray Code. Be good...
"; clientCode($mouse); echo "\n"; echo "Subchain: Squirrel > Dog
"; clientCode($squirrel);