(六)面向对象的设计原则之二

一.简介:
命令模式:命令模式分为“命令的请求者”和“命令的实现者”。使得命令的请求和实现完成了解耦。

二.示例:

<?php
/*
 * 模拟服务员与厨师
 */
class MealCommand implements Command{
    private $cook;
    public function __construct(cook $cook){
        $this->cook = $cook;
    }
    public function execute(){
        $this->cook->meal();
    }
}

class DrinkCommand implements Command{
    private $cook;
    public function __construct(cook $cook){
        $this->cook = $cook;
    }

    public function execute(){
        $this->cook->drink();
    }
}

/*
 * 模拟类
 */
class cookControl{
    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();
    }
}

$control = new cookControl();
$cook = new cook;
$mealCommand = new MealCommand($cook);
$drinkCommand = new DrinkCommand($cook);
$control->addCommand($mealCommand,$drinkCommand);
$control->callMeal();
$control->callDrink();

三.使用原则:

1.根据业务流程,提炼业务流程。一步步抽象直至‘恰当’。
2.职责分类需要注意。

你可能感兴趣的:(PHP,面向对象,设计,设计原则,命令模式)