Skip to content

Instantly share code, notes, and snippets.

@xwlee
Last active December 14, 2015 03:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xwlee/87b417a7ee5b5c77ce20 to your computer and use it in GitHub Desktop.
Save xwlee/87b417a7ee5b5c77ce20 to your computer and use it in GitHub Desktop.
<?php
abstract class enemyShip {
protected $name;
protected $amtDamage;
public function setName($newName) {
$this->name = $newName;
}
public function getName() {
return $this->name;
}
public function setDamage($newDamage) {
$this->amtDamage = $newDamage;
}
public function getDamage() {
return $this->amtDamage;
}
public function followHeroShip() {
echo $this->getName() . " is following the hero <br/>";
}
public function displayEnemyShip() {
echo $this->getName() . " is on the screen <br />";
}
public function enemyShipShoots() {
echo $this->getName() . " attack and does " . $this->getDamage() . "<br />";
}
}
class UFOEnemyShip extends enemyShip {
public function __construct() {
parent::setName("UFO Enemy Ship");
parent::setDamage(20);
}
}
class RocketEnemyShip extends enemyShip {
public function __construct() {
parent::setName("Rocket Enemy Ship");
parent::setDamage(10);
}
}
class BigUFOEnemyShip extends UFOEnemyShip {
public function __construct() {
parent::setName("BigUFO Enemy Ship");
parent::setDamage(40);
}
}
class EnemyShipFactory {
// Encapsulate ship creation
// When we have to modify something, this is the only one place where we gonna have to make those modifications
public function makeEnemyShip($newShipType) {
if ($newShipType == "u") {
return new UFOEnemyShip();
} elseif ($newShipType == "r") {
return new RocketEnemyShip();
} elseif ($newShipType == "b") {
return new BigUFOEnemyShip();
}
}
}
// After using Factory Design Pattern
class enemyShipTesting {
public function __construct() {
if (isset($_POST['type'])) {
$factory = new EnemyShipFactory();
$ufoShip = $factory->makeEnemyShip($_POST['type']);
$this->doStuffEnemy($ufoShip);
}
echo '<form method="post">',
'<label for="type">Type: </label>',
'<input type"text" id="type" name="type" />',
'</form>';
}
public function doStuffEnemy(enemyShip $anEnemyShip) {
$anEnemyShip->followHeroShip();
$anEnemyShip->displayEnemyShip();
$anEnemyShip->enemyShipShoots();
}
}
$testing = new enemyShipTesting();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment