设计模式 命令模式

WechatIMG39.jpeg

介绍

命令模式是一种行为设计模式,它将请求封装为一个对象,从而使不同的请求可以被参数化、队列化、记录日志,或者支持撤销等操作。

角色

角色 说明
Command 抽象命令类
ConcreteCommand 具体命令类
Invoker 调用者
Receiver 接收者
Client 客户类

角色示例

类名 担任角色 说明
Command 抽象命令 抽象命令类
StartCommand 具体命令 启动命令类
StopCommand 具体命令 停止命令类
RemoteController 调用者 遥控器类
AirConditioner 接收者 空调类
User 客户 用户类

UML类图

命令模式.jpg

代码

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
<?php 
class AirConditioner
{
public function start()
{
return "启动空调".PHP_EOL;
}

public function stop()
{
return "关闭空调".PHP_EOL;
}
}

abstract class Command
{
protected $airConditioner;
function __construct(AirConditioner $airConditioner)
{
$this->airConditioner = $airConditioner;
}
abstract public function execute();
}

class StartCommand extends Command
{
function __construct(AirConditioner $airConditioner)
{
parent::__construct($airConditioner);
}

public function execute()
{
return $this->airConditioner->start();
}
}

class StopCommand extends Command
{
function __construct(AirConditioner $airConditioner)
{
parent::__construct($airConditioner);
}

public function execute()
{
return $this->airConditioner->stop();
}
}

class RemoteController
{
protected $command;
function __construct(Command $command)
{
$this->command = $command;
}

public function control()
{
return $this->command->execute();
}
}

class User
{
public function setCommand(Command $command){
return (new remoteController($command))->control();
}
}

$user = new User();
$airConditioner = new AirConditioner();

$startCommand = new StartCommand($airConditioner);
echo $user->setCommand($startCommand);

$stopCommand = new StopCommand($airConditioner);
echo $user->setCommand($stopCommand);

创建 Command.php,内容如上。

执行

1
2
3
$ php Command.php
启动空调
关闭空调
-------------本文结束感谢您的阅读-------------
0%