-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstrategy.php
More file actions
53 lines (41 loc) · 1015 Bytes
/
strategy.php
File metadata and controls
53 lines (41 loc) · 1015 Bytes
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
<?php
/*
strategy pattern :
best used when classes differ only in their behavior
define a class of algorithms
*/
interface Behavior {
public function movement();
}
class NormalBehavior implements Behavior {
public function movement() {
print "I am a normal robot\n";
}
}
class AggressiveBehavior implements Behavior {
public function movement() {
print "I am an aggressive robot\n";
}
}
class Robot {
private $behavior;
private $name;
public function __construct($name) {
$this->name = $name;
}
public function setBehavior(Behavior $behavior) {
$this->behavior = $behavior;
}
public function movement() {
$this->behavior->movement();
}
}
$normalBehavior = new NormalBehavior;
$aggressiveBehavior = new AggressiveBehavior;
$robot = new Robot("Mr. Passive");
$robot->setBehavior($normalBehavior);
$robot->movement();
$robot = new Robot("Mr. Passive-Aggressive");
$robot->setBehavior($aggressiveBehavior);
$robot->movement();
?>