喜迎
春节

设计模式——命令模式


说明

示例

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

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();
// output: command received!

总结


文章作者: Crazy Boy
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Crazy Boy !
评 论
 上一篇
设计模式——代理模式
设计模式——代理模式
说明其实每个模式名称就表明了该模式的作用,代理模式就是多一个代理类出来,替原对象进行一些操作,比如我们在租房子的时候回去找中介,为什么呢?因为你对该地区房屋的信息掌握的不够全面,希望找一个更熟悉的人去帮你做,此处的代理就是这个意思。再如我们
2022-05-19
下一篇 
设计模式——备忘录模式
设计模式——备忘录模式
说明示例下面看下备忘录模式的代码实现 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
2022-05-19
  目录
hexo