<?php
header("Content-Type:text/html;charset=utf-8");
/**
*
* @php设计模式之命令模式
* @命令模式顾名思义,下达命令,接收命令,执行命令
* @本例主要模拟古时皇帝给下面的人下达命令来解释什么是命令模式
**/
//执行命令
class Minitary
{
//执行派兵
public function battle()
{
echo '派兵打仗'.PHP_EOL;
}
}
class Kitchen
{
//执行做饭
public function cook()
{
echo '做好吃的';
}
}
/**
*命令统一执行接口
**/
interface Command{ public function execute();}
/**
*
* 兵部需要执行 打仗命令
**/
class BattleCommand implements Command
{
//发兵令牌
protected $_military;
public function __construct(Minitary $minitary)
{
$this->_military=$minitary;
}
public function execute()
{
$this->_military->battle();
}
}
/**
*
* 御膳房需要执行 做饭命令
**/
class CookCommand implements Command
{
//做饭令牌
protected $_kitchen;
public function __construct(Kitchen $kitchen)
{
$this->_kitchen=$kitchen;
}
public function execute()
{
$this->_kitchen->cook();
}
}
/**
*
*接下来,我们看下太监能干什么?他只需要知道是什么命令,去传就可以了。
**/
class Taijian
{
/**
*这是什么命令
*/
protected $_command;
public function __construct(Command $command)
{
$this->_command=$command;
}
public function sendCommand()
{
$this->_command->execute();
}
}
/**
*到此二B皇帝只需要发号施令就可以了
*
**/
class King
{
public function doCommand()
{
//让一个太监给兵部发送派兵打仗的命令.
$tj1=new Taijian(new BattleCommand(new Minitary));
$tj1->sendCommand();
//让一个太监给御善房发送做饭的命令.
$tj2=new Taijian(new CookCommand(new Kitchen));
$tj2->sendCommand();
}
}
$king=new King;
$king->doCommand();
?>
学习QQ群:193990134