Skip to content

Instantly share code, notes, and snippets.

@ken-master
Last active August 29, 2015 14:23
Show Gist options
  • Save ken-master/95eccc7352470d56f91b to your computer and use it in GitHub Desktop.
Save ken-master/95eccc7352470d56f91b to your computer and use it in GitHub Desktop.
PHP Strategy Pattern example
<?Php
/**
* Create the INTERFACE
**/
interface CharacterInterface{
public function attack();
public function dodge();
public function heal();
}
abstract CharacterAbstract implements CharacterInterface{
public function attack();
public function dodge();
public function heal();
}
/* Concrete CLASS */
class Archer extends Character{
protected $_hp;
public function attack()
{
return 100;
}
public function dodge()
{
return 'miss';
}
public function heal()
{
return $this->hp + 100;
}
}
/* Concrete CLASS */
class Warrior extends CharacterAbstract{
protected $_hp;
public function attack()
{
return 150;
}
public function dodge()
{
return 'miss';
}
public function heal()
{
return $this->hp + 100;
}
}
/** CLient Class **/
class Character{
protected $character;
public function __construct(CharacterAbstract $character){
$this->character = new $character();
}
}
/** Implementation **/
$archer = new Character( 'Archer' );
$archer->attack();
$archer->dodge();
$archer->heal();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment