-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathstate.php
88 lines (75 loc) · 2.26 KB
/
state.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php
class BookContext {
private $book = NULL;
private $bookTitleState = NULL;
//bookList is not instantiated at construct time
public function __construct($book_in) {
$this->book = $book_in;
$this->setTitleState(new BookTitleStateStars());
}
public function getBookTitle() {
return $this->bookTitleState->showTitle($this);
}
public function getBook() {
return $this->book;
}
public function setTitleState($titleState_in) {
$this->bookTitleState = $titleState_in;
}
}
interface BookTitleStateInterface {
public function showTitle($context_in);
}
class BookTitleStateExclaim implements BookTitleStateInterface {
private $titleCount = 0;
public function showTitle($context_in) {
$title = $context_in->getBook()->getTitle();
$this->titleCount++;
$context_in->setTitleState(new BookTitleStateStars());
return Str_replace(' ','!',$title);
}
}
class BookTitleStateStars implements BookTitleStateInterface {
private $titleCount = 0;
public function showTitle($context_in) {
$title = $context_in->getBook()->getTitle();
$this->titleCount++;
if (1 < $this->titleCount) {
$context_in->setTitleState(new BookTitleStateExclaim);
}
return Str_replace(' ','*',$title);
}
}
class Book {
private $author;
private $title;
function __construct($title_in, $author_in) {
$this->author = $author_in;
$this->title = $title_in;
}
function getAuthor() {return $this->author;}
function getTitle() {return $this->title;}
function getAuthorAndTitle() {
return $this->getTitle() . ' by ' . $this->getAuthor();
}
}
writeln('BEGIN TESTING STATE PATTERN');
writeln('');
$book = new Book('PHP for Cats','Larry Truett');;
$context = new bookContext($book);
writeln('test 1 - show name');
writeln($context->getBookTitle());
writeln('');
writeln('test 2 - show name');
writeln($context->getBookTitle());
writeln('');
writeln('test 3 - show name');
writeln($context->getBookTitle());
writeln('');
writeln('test 4 - show name');
writeln($context->getBookTitle());
writeln('');
writeln('END TESTING STATE PATTERN');
function writeln($line_in) {
echo $line_in."<br/>";
}