Wzorzec Strategia definiuje grupę algorytmów, które mogą być stosowane wymiennie w trakcie działania programu. Interfejs wzorca określa zadania (operacje), które implementują konkretne strategie (KonkretnaStrategiaA, KonkretnaStrategiaB, …). Klasa Kontekst ustawia referencję do interfejsu Strategia oraz implementuje metodę kontekstu, która umożliwia dynamiczną zmianę używanej strategii.
PRZYKŁAD
W przykładzie wykorzystam strategie do zmiany formatowania wyświetlanego tekstu (duże litery, małe litery, pierwsza litera duża, pierwsza litera mała).
Na początku dodamy interfejs Strategy i zdefiniujemy w nim funkcję format($text). Jak łatwo się domyśleć, funkcja będzie przyjmować tekst do sformatowania.
1 2 3 4 5 6 7 |
<?php // Strategy.php interface Strategy { public function format($text); } ?> |
Dodajmy teraz konkretne strategie, które zaimplementują interfejs strategii i metodę format:
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php // Uppercase.php class Uppercase implements Strategy { private $text; public function format($text) { $this->text = $text; echo strtoupper($this->text); } } ?> |
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php // Lowercase.php class Lowercase implements Strategy { private $text; public function format($text) { $this->text = $text; echo strtolower($this->text); } } ?> |
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php // Ucfirst.php class Ucfirst implements Strategy { private $text; public function format($text) { $this->text = $text; echo ucfirst($this->text); } } ?> |
1 2 3 4 5 6 7 8 9 10 11 12 |
<?php // Lcfirst.php class Lcfirst implements Strategy { private $text; public function format($text) { $this->text = $text; echo lcfirst($this->text); } } ?> |
Klasa Context jest tutaj najistotniejsza. Metoda format wykonuje formatowanie konkretnej strategii zapodanej w konstruktorze:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php // Context.php class Context { private $strategy; private $text; public function __construct(Strategy $strategy) { $this->strategy = $strategy; } public function format($text) { $this->text = $text; $this->strategy->format($this->text); } } ?> |
Tworzymy klasę klienta i testujemy działanie programu:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php // Client.php spl_autoload_register(function ($class_name) { include $class_name . '.php'; }); $text = 'example string'; $context = new Context(new Uppercase()); $context->format($text); // EXAMPLE STRING echo '<hr />'; $context = new Context(new Lowercase()); $context->format($text); // example string echo '<hr />'; $context = new Context(new Ucfirst()); $context->format($text); // Example string echo '<hr />'; $context = new Context(new Lcfirst()); $context->format($text); // example string ?> |