Last active
August 29, 2015 14:19
-
-
Save harunyasar/17bb0e86c52d33b06256 to your computer and use it in GitHub Desktop.
PHP Design Patterns: Command Pattern
This file contains 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 | |
// Command | |
interface Order { | |
public function execute(); | |
} | |
// Receiver Class | |
class Stock { | |
private $name = "ABC"; | |
private $quantity = 10; | |
public function buy() { | |
echo "Stock [Name: $this->name, Quantity: $this->quantity] bought\n"; | |
} | |
public function sell() { | |
echo "Stock [Name: $this->name, Quantity: $this->quantity] sold\n"; | |
} | |
} | |
class BuyStock implements Order { | |
private $abcStock; | |
public function BuyStock(Stock $abcStock){ | |
$this->abcStock = $abcStock; | |
} | |
public function execute() { | |
$this->abcStock->buy(); | |
} | |
} | |
class SellStock implements Order { | |
private $abcStock; | |
public function SellStock(Stock $abcStock){ | |
$this->abcStock = $abcStock; | |
} | |
public function execute() { | |
$this->abcStock->sell(); | |
} | |
} | |
class Broker { | |
private $orderList = array(); | |
public function takeOrder(Order $order) { | |
array_push($this->orderList, $order); | |
} | |
public function placeOrders() { | |
foreach($this->orderList as $order) { | |
$order->execute(); | |
} | |
unset($orderList); | |
} | |
} | |
// Invoker | |
$stock = new Stock(); | |
$buyStock = new BuyStock($stock); | |
$sellStock = new SellStock($stock); | |
$broker = new Broker(); | |
$broker->takeOrder($buyStock); | |
$broker->takeOrder($sellStock); | |
$broker->placeOrders(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment