一.簡介:
命令模式:命令模式分為「命令的請求者」和「命令的實現者」。使得命令的請求和實作完成了解耦。
二.例:
<?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();
版權聲明:本文為部落客原創文章,未經部落客允許不得轉載。
以上就介紹了(六)物件導向的設計原則之二,包括了面向的內容,希望對PHP教學有興趣的朋友有幫助。