Skip to content

Commit

Permalink
strategy pattern
Browse files Browse the repository at this point in the history
  • Loading branch information
gabrielfs7 committed Aug 11, 2014
1 parent 62e7c96 commit c27056a
Show file tree
Hide file tree
Showing 2 changed files with 104 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/GSoares/DesignPatterns/Behavioral/Strategy/README.md
Original file line number Diff line number Diff line change
@@ -1 +1,5 @@
#Strategy - Design Patterns#
#Strategy - Design Patterns#

Encapsula um algorítimo dentro de uma classe.

Baseado no OCP (Open closed principle).
99 changes: 99 additions & 0 deletions src/GSoares/DesignPatterns/Behavioral/Strategy/Sample.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
<?php
namespace GSoares\DesignPatterns\Behavioral\Strategy;

class Driver
{
private $mainVehicle;

public function __construct(Vehicle $mainVehicle)
{
$this->mainVehicle = $mainVehicle;
}

public function isPilot()
{
return $this->mainVehicle instanceof Airplane;
}

public function isTaxiDriver()
{
return $this->mainVehicle instanceof Taxi;
}

public function isBiker()
{
return $this->mainVehicle instanceof Bike;
}
}


interface Vehicle
{
public function run();
}

class Airplane implements Vehicle
{
public function run()
{
echo "Running airplane...\n";
}
}

class Bike implements Vehicle
{
public function run()
{
echo "Running bike...\n";
}
}

class Taxi implements Vehicle
{
public function run()
{
echo "Running taxi...\n";
}
}

class StrategyContext
{
private $vehicle;

public function __construct(Driver $driver)
{
if ($driver->isPilot()) {
$this->vehicle = new Airplane();

return;
}

if ($driver->isTaxiDriver()) {
$this->vehicle = new Taxi();

return;
}

if ($driver->isBiker()) {
$this->vehicle = new Bike();

return;
}
}

public function runVehicle()
{
return $this->vehicle->run();
}
}

function runStrategy()
{
$bikerContext = new StrategyContext(new Driver(new Bike()));
$pilotContext = new StrategyContext(new Driver(new Airplane()));
$taxiDriverContext = new StrategyContext(new Driver(new Taxi()));

$bikerContext->runVehicle();
$pilotContext->runVehicle();
$taxiDriverContext->runVehicle();
}

0 comments on commit c27056a

Please sign in to comment.