命令模式 - 设计模式 - PHP版
2021-05-18 16:27
标签:his div nts 客户 serve ice cut 客户端 echo 命令模式 - 设计模式 - PHP版 标签:his div nts 客户 serve ice cut 客户端 echo 原文地址:http://www.cnblogs.com/benben7466/p/7736562.html 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版
文章链接:http://soscw.com/index.php/essay/87260.html