The Chain of Responsibility
Let's create a PHP example:
The first thing I want to create is the interface Handler. We add the two method definitions:
public function setNext(Handler $handler): Handler; public function handle(string $request): ?string;Next we create a class called AbstractHandler it implements Handler and missing methods setNext and handle
we add code to setNext and to handle
$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 . ".let's add another anamale DogHandler
"; } else { return parent::handle($request); } }
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 . ".for our demo we go to the index.php file and add sime includes:
"; } else { return parent::handle($request); } }
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 . "?next we define the following local varables:
"; $result = $handler->handle($food); if ($result) { echo " " . $result; } else { echo " " . $food . " was left untouched."; } } }
$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);