Repository navigation
Expand file tree
/
Copy pathcommand.php
More file actions
117 lines (84 loc) · 2.48 KB
/
Copy pathcommand.php
File metadata and controls
117 lines (84 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
<?php
/**
* 命令模式
*
* 将一个请求封装为一个对象从而使你可用不同的请求对客户进行参数化,对请求排除或记录请求日志,以及支持可取消的操作
*/
interface Command {
public function execute();
}
class Invoker {
private $_command = array();
public function setCommand($command) {
$this->_command[] = $command;
}
public function executeCommand() {
foreach ($this->_command as $command) {
$command->execute();
}
}
public function removeCommand($command) {
$key = array_search($command, $this->_command);
if ($key !== false) {
unset($this->_command[$key]);
}
}
}
class Receiver {
private $_name = null;
public function __construct($name) {
$this->_name = $name;
}
public function action() {
echo $this->_name . " action<br/>";
}
public function action1() {
echo $this->_name . " action1<br/>";
}
}
class ConcreteCommand implements Command {
private $_receiver;
public function __construct($receiver) {
$this->_receiver = $receiver;
}
public function execute() {
$this->_receiver->action();
}
}
class ConcreteCommand1 implements Command {
private $_receiver;
public function __construct($receiver) {
$this->_receiver = $receiver;
}
public function execute() {
$this->_receiver->action1();
}
}
class ConcreteCommand2 implements Command {
private $_receiver;
public function __construct($receiver) {
$this->_receiver = $receiver;
}
public function execute() {
$this->_receiver->action();
$this->_receiver->action1();
}
}
$objRecevier = new Receiver("No.1");
$objRecevier1 = new Receiver("No.2");
$objRecevier2 = new Receiver("No.3");
$objCommand = new ConcreteCommand($objRecevier);
$objCommand1 = new ConcreteCommand1($objRecevier);
$objCommand2 = new ConcreteCommand($objRecevier1);
$objCommand3 = new ConcreteCommand1($objRecevier1);
$objCommand4 = new ConcreteCommand2($objRecevier2); // 使用 Recevier的两个方法
$objInvoker = new Invoker();
$objInvoker->setCommand($objCommand);
$objInvoker->setCommand($objCommand1);
$objInvoker->executeCommand();
$objInvoker->removeCommand($objCommand1);
$objInvoker->executeCommand();
$objInvoker->setCommand($objCommand2);
$objInvoker->setCommand($objCommand3);
$objInvoker->setCommand($objCommand4);
$objInvoker->executeCommand();