命令模式 - 设计模式 - PHP版
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了命令模式 - 设计模式 - PHP版相关的知识,希望对你有一定的参考价值。
1 <?php 2 /* 3 * 命令模式 4 * 5 */ 6 //声明执行操作的接口(Command接口) 7 interface Cook { 8 public function excute(); 9 } 10 //做米饭(ConcreteCommand) 11 class CookRice implements Cook { 12 private $cooker; 13 function __construct(Cooker $cooker) { 14 $this->cooker = $cooker; 15 } 16 public function excute() { 17 $this->cooker->doRice(); 18 } 19 } 20 //做菜(ConcreteCommand) 21 class CookFood implements Cook { 22 private $cooker; 23 function __construct(Cooker $cooker) { 24 $this->cooker = $cooker; 25 } 26 public function excute() { 27 $this->cooker->doFood(); 28 } 29 } 30 //服务员(Invoker)(通过List方式,可以进一步优化,这里略) 31 class ServerPerson { 32 private $cook; 33 public function setCook(Cook $cook) { 34 $this->cook = $cook; 35 } 36 public function ExecuteCommand() { 37 $this->cook->excute(); 38 } 39 } 40 //厨师(Receiver) 41 class Cooker { 42 public function doRice() { 43 echo ‘做饭‘; 44 } 45 public function doFood() { 46 echo ‘做菜‘; 47 } 48 } 49 //客户端 50 class Client { 51 public static function main() { 52 $cooker = new Cooker(); 53 $server = new ServerPerson(); 54 //做饭 55 $cookA = new CookRice($cooker); 56 $server->setCook($cookA); 57 $server->ExecuteCommand(); 58 //做菜 59 $cookB = new CookFood($cooker); 60 $server->setCook($cookB); 61 $server->ExecuteCommand(); 62 } 63 } 64 Client::main();
以上是关于命令模式 - 设计模式 - PHP版的主要内容,如果未能解决你的问题,请参考以下文章