Command_命令模式_PHP语言描述

<?php

	/*
	 * 这是一个宏命令的实例,是相对复杂一点的Command设计模式的用例
	 * 这个用例主要是模拟餐厅点餐的过程,在这个用例里服务员即是Command模式中的Client+Invoker
         * 命令必须持有具体实现功能的对象
	 */

	//厨师的接口
	interface cookApi{
		public function cook($name);
	}

	//厨师对象,做热菜
	class HotCook implements cookApi{
		public function cook($name){
			echo "热菜厨师正在做:".$name."<br>";
		}
	}
	
	//厨师对象,做冷菜
	class CoolCook implements cookApi{
		public function cook($name){
			echo "冷菜厨师正在做:".$name."<br>";
		}
	}
	
	//命令接口
	interface Command{
		public function execute();
	}
	
	//具体的命令对象,需持有相应的具体处理事务的类实例。这里咱们做三个命令对象,即菜品"绿豆排骨煲"、"北京烤鸭"、"蒜泥白肉(凉菜)"
	
	class ChopCommand implements Command{
		//持有具体的厨师对象
		private $cookApi = NULL;
		
		//设置具体的厨师对象
		public function setCookApi($cookApi){
			$this->cookApi = $cookApi;
		}
		
		public function execute(){
			$this->cookApi->cook("绿豆排骨煲");
		}
	}
	
	class DuckCommand implements Command{
		//持有具体的厨师对象
		private $cookApi = NULL;
		
		//设置具体的厨师对象
		public function setCookApi($cookApi){
			$this->cookApi = $cookApi;
		}
		
		public function execute(){
			$this->cookApi->cook("北京烤鸭");
		}
	}
	
	class PorkCommand implements Command{
		//持有具体的厨师对象
		private $cookApi = NULL;
		
		//设置具体的厨师对象
		public function setCookApi($cookApi){
			$this->cookApi = $cookApi;
		}
		
		public function execute(){
			$this->cookApi->cook("蒜泥白肉");
		}
	}
	
	//菜单对象,是一个宏命令对象,宏命令顾名思义就是一组命令的集合,当执行宏命令时,需要依次执行所有的命令
	class MenuCommand implements Command{
		private $commandArr = array();
		 
		//点菜,把菜品加入到点菜单中
		public function addCommand($command){
			array_push($this->commandArr, $command);
		}
		//执行菜单命令
		public function execute(){
			foreach ($this->commandArr as $key => $value) {
				$this->commandArr[$key]->execute();
			}
		}
	}
	
	/*
	 * 服务员类,负责组合菜单,负责组装每个菜和具体的实现者即厨师
	 * 还负责执行调用,相当于标准Command模式的Client+Invoker
	 */
	
	class Waiter{
		
		//持有一个菜单对象,即宏命令对象
		private $menuCommand;
		
		public function __construct(){
			$this->menuCommand = new MenuCommand();
		}
		
		public function orderDish($cmd){
			//客户传过来的命令对象是没有和接受者组装的
			//在这里组装,因为客户并不知道他点的菜是谁来做,凉菜热菜是否不是一个人做,这些都不是客户应该关心的。
			$hotCook = new HotCook();
			$cookCook = new CoolCook();
			if($cmd instanceof DuckCommand){
				$cmd->setCookApi($hotCook);
			}
			else if($cmd instanceof ChopCommand){
				$cmd->setCookApi($hotCook);
			}
			else if($cmd instanceof PorkCommand){
				$cmd->setCookApi($cookCook);
			}
			$this->menuCommand->addCommand($cmd);
		}
		
		public function orderOver(){
			$this->menuCommand->execute();
		}
		
	}
	
	$waiter = new Waiter();
	
	$chop = new ChopCommand();
	$duck = new DuckCommand();
	$pork = new PorkCommand();
	
	$waiter->orderDish($chop);
	$waiter->orderDish($duck);
	$waiter->orderDish($pork);
	
	$waiter->orderOver();
	?>


你可能感兴趣的:(PHP,command,命令模式)