设计模式—命令模式

命令模式

设计模式里面,命令模式也是遵循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();

从上面的例子我们可以看出,设计模式并非是纯理论的,可以借鉴生活中的例子来加以理解

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值