-
-
Save ancarebeca/b4696d95cf446b82f70253da3d4f54ec to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Context | |
{ | |
private $strategy; | |
public function __construct(StrategyInterface $strategy) | |
{ | |
$this->strategy = $strategy; | |
} | |
public function applyStrategy(Book $book) | |
{ | |
return $this->strategy->formatTitle($book); | |
} | |
} | |
interface StrategyInterface | |
{ | |
public function formatTitle(Book $book); | |
} | |
class StrategyUppercase implements StrategyInterface | |
{ | |
public function formatTitle(Book $book) | |
{ | |
return strtoupper($book->getTitle()); | |
} | |
} | |
class StrategyLowercase implements StrategyInterface | |
{ | |
public function formatTitle(Book $book) | |
{ | |
return strtolower($book->getTitle()); | |
} | |
} | |
class StrategyLcfirst implements StrategyInterface | |
{ | |
public function formatTitle(Book $book) | |
{ | |
return lcfirst($book->getTitle()); | |
} | |
} | |
class StrategyUcwords implements StrategyInterface | |
{ | |
public function formatTitle(Book $book) | |
{ | |
return ucwords($book->getTitle()); | |
} | |
} | |
class Book | |
{ | |
private $title; | |
function __construct(string $title_in) | |
{ | |
$this->title = $title_in; | |
} | |
function getTitle(): string | |
{ | |
return $this->title; | |
} | |
} | |
$book = new Book('Harry Potter'); | |
echo "Title: " . $book->getTitle()."<br/>"; | |
$strategyUppercase = new StrategyUppercase(); | |
$context = new Context($strategyUppercase); | |
echo "Strategy uppercase: " . $context->applyStrategy($book)."<br/>"; | |
$strategyLowercase = new StrategyLowercase(); | |
$context = new Context($strategyLowercase); | |
echo "Strategy lowercase: " . $context->applyStrategy($book)."<br/>"; | |
$strategyLcfirst = new StrategyLcfirst(); | |
$context = new Context($strategyLcfirst); | |
echo "Strategy first character in lowercase: " . $context->applyStrategy($book)."<br/>"; | |
/**** Output: *************************************** | |
* Title: Harry Potter | |
* Strategy uppercase: HARRY POTTER | |
* Strategy lowercase: harry potter | |
* Strategy first character in lowercase: harry Potter | |
*****************************************************/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment