Created
April 9, 2012 16:43
-
-
Save Chavao/2344644 to your computer and use it in GitHub Desktop.
Exemplo de Strategy
This file contains hidden or 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 | |
interface IStrategy | |
{ | |
public function mover(); | |
public function falar(); | |
} | |
class Strategy implements IStrategy { | |
private $objeto; | |
public function __construct($p_objeto) | |
{ | |
$this->objeto = $p_objeto; | |
} | |
public function mover() | |
{ | |
$this->objeto->mover(); | |
} | |
public function falar() | |
{ | |
$this->objeto->falar(); | |
} | |
} | |
class MySQL implements IStrategy { | |
public function mover() | |
{ | |
echo "Moveu com MySQL"; | |
} | |
public function falar(); | |
{ | |
echo "MySQL falou!"; | |
} | |
} | |
class Oracle implements IStrategy { | |
public function mover() | |
{ | |
echo "Moveu com Oracle"; | |
} | |
public function falar(); | |
{ | |
echo "Oracle falou!"; | |
} | |
} | |
$obj = new Strategy(new MySQL()); | |
$obj->mover(); // Retornará: Moveu com MySQL | |
$obj->falar(); // Retornará: MySQL falou! | |
$obj = new Strategy(new Oracle()); | |
$obj->mover(); // Retornará: Moveu com Oracle | |
$obj->falar(); // Retornará: Oracle falou! | |
// Perceba que o objeto é o mesmo, ele só recebe a instância | |
// do objeto certo e então faz as estratégias certas. | |
// Com iterador você faria isso, o iterador não trataria queries de forma normal | |
// ele simplesmente faria essa interface, e quando vocẽ chamasse o ->next(); | |
// por trás dos panos ele chamaria a instancia do banco que tivesse implementado | |
// | |
// Ex: | |
// interface IStrategy | |
// { | |
// public function next(); | |
// } | |
// | |
// class IteratorStrategy implements IStrategy { | |
// private $objeto; | |
// | |
// function __construct($p_objeto) | |
// { | |
// $this->objeto = $p_objeto; | |
// } | |
// | |
// function next() | |
// { | |
// $this->objeto->next(); | |
// } | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment