喜迎
春节

设计模式——命令模式


说明

示例

下面看下命令模式的代码实现

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
// 创建接口Command
interface Command{
public function exe();
}

class Receiver{
public function action(){
echo "command received!";
}
}

// 类MyCommand实现接口Command
class MyCommand implements Command{
private Receiver $receiver;
public function __construct(Receiver $receiver){
$this->receiver = $receiver;
}

public function exe(){
$this->receiver->action();
}
}

class Invoker{
private Command $command;
public function __construct(Command $command){
$this->command = $command;
}
public function action(){
$this->command->exe();
}
}


// 调用
$receiver = new Receiver();
$cmd = new MyCommand($receiver);
$invoker = new Invoker($cmd);
$invoker->action();
// 创建接口Command
interface Command{
public function exe();
}

class Receiver{
public function action(){
echo "command received!";
}
}

// 类MyCommand实现接口Command
class MyCommand implements Command{
private Receiver $receiver;
public function __construct(Receiver $receiver){
$this->receiver = $receiver;
}

public function exe(){
$this->receiver->action();
}
}

class Invoker{
private Command $command;
public function __construct(Command $command){
$this->command = $command;
}
public function action(){
$this->command->exe();
}
}


// 调用
$receiver = new Receiver();
$cmd = new MyCommand($receiver);
$invoker = new Invoker($cmd);
$invoker->action();
// output: command received!

总结


文章作者: Crazy Boy
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Crazy Boy !
评 论
 上一篇
设计模式——原型模式
设计模式——原型模式
说明 将一个对象作为原型,对其进行复制、克隆,产生一个和原对象类似的新对象。 示例下面看下原型模式的代码实现 12345678910111213141516171819202122232425262728293031323334353
2022-05-19
下一篇 
设计模式——备忘录模式
设计模式——备忘录模式
说明示例下面看下备忘录模式的代码实现 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
2022-05-19
  目录