命令模式
设计模式里面,命令模式也是遵循SRP(Single Responsibility Principle)原则。命令模式分离了“命令的请求者”与“命令的实现者”。
例如我们生活中最典型的餐馆中的“顾客”,“服务员”,“厨师”三种角色:
- 顾客只负责点菜,传递给服务员
- 服务员通知厨师炒菜
- 厨师炒菜
上面的例子,就是典型的命令模式。代码如下:
<?php
/**
* 厨师类,命令的接受者与执行者
* Class Cook
*/
class Cook{
public function meal(){
echo '番茄炒鸡蛋'.PHP_EOL;
}
public function drink(){
echo '紫菜的蛋汤'.PHP_EOL;
}
public function ok(){
echo '完毕'.PHP_EOL;
}
}
/**
* 命令接口
* Interface Command
*/
interface Command{
public function execute();
}
/**
* 服务员类实现1
* Class MealCommand
*/
class MealCommand implements Command{
private $cook;
function __construct(Cook $cook){
$this->cook = $cook;
}
public function execute(){
$this->cook->meal();
}
}
/**
* 服务员类实现2
* Class DrinkCommand
*/
class DrinkCommand implements Command{
private $cook;
function __construct(Cook $cook){
$this->cook = $cook;
}
public function execute(){
$this->cook->drink();
}
}
/**
* 客户点菜类
* Class Customer
*/
class Customer{
private $mealCommand;
private $drinkCommand;
public function addCommand(Command $mealCommand,Command $drinkCommand){
$this->mealCommand = $mealCommand;
$this->drinkCommand = $drinkCommand;
}
public function callMeal(){
$this->mealCommand->execute();
}
public function callDrink(){
$this->drinkCommand->execute();
}
}
/**
* 实现如下
*/
$customer = new Customer();
$cook = new Cook();
$mealCommand = new MealCommand($cook);
$drinkCommand = new DrinkCommand($cook);
$customer->addCommand($mealCommand,$drinkCommand);
$customer->callMeal();
$customer->callDrink();
从上面的例子我们可以看出,设计模式并非是纯理论的,可以借鉴生活中的例子来加以理解