-
Notifications
You must be signed in to change notification settings - Fork 0
/
command_pattern.php
65 lines (51 loc) · 1.3 KB
/
command_pattern.php
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
<?php
// The command pattern is a behavioral design pattern in which
// an object is used to represent and encapsulate all the information needed to call a method at a later time.
namespace commandPattern;
class CakeControl
{
private $type;
public function __construct($type)
{
$this->type = $type;
}
public function makeCake() {
echo "making $this->type..." . PHP_EOL;
}
public function destroyCake() {
echo "don't like $this->type? OK, I'll throw it :(" . PHP_EOL;
}
}
interface Command
{
public function execute();
}
class MakeCakeCommand implements Command
{
private $cakeControl;
public function __construct($cakeControl)
{
$this->cakeControl = $cakeControl;
}
public function execute()
{
$this->cakeControl->makeCake();
}
}
class DestroyCakeCommand implements Command
{
private $cakeControl;
public function __construct($cakeControl)
{
$this->cakeControl = $cakeControl;
}
public function execute()
{
$this->cakeControl->destroyCake();
}
}
$cakeControl = new CakeControl("cheese cake");
$makeCakeCommand = new MakeCakeCommand($cakeControl);
$makeCakeCommand->execute();
$destroyCakeCommand = new DestroyCakeCommand($cakeControl);
$destroyCakeCommand->execute();