-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathsingleton.php
More file actions
105 lines (84 loc) · 2.35 KB
/
Copy pathsingleton.php
File metadata and controls
105 lines (84 loc) · 2.35 KB
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<?php
/*
* Singleton classes
*/
class BookSingleton {
private $author = 'Gamma, Helm, Johnson, and Vlissides';
private $title = 'Design Patterns';
private static $book = NULL;
private static $isLoanedOut = FALSE;
private function __construct() {
}
static function borrowBook() {
if (FALSE == self::$isLoanedOut) {
if (NULL == self::$book) {
self::$book = new BookSingleton();
}
self::$isLoanedOut = TRUE;
return self::$book;
} else {
return NULL;
}
}
function returnBook(BookSingleton $bookReturned) {
self::$isLoanedOut = FALSE;
}
function getAuthor() {return $this->author;}
function getTitle() {return $this->title;}
function getAuthorAndTitle() {
return $this->getTitle() . ' by ' . $this->getAuthor();
}
}
class BookBorrower {
private $borrowedBook;
private $haveBook = FALSE;
function __construct() {
}
function getAuthorAndTitle() {
if (TRUE == $this->haveBook) {
return $this->borrowedBook->getAuthorAndTitle();
} else {
return "I don't have the book";
}
}
function borrowBook() {
$this->borrowedBook = BookSingleton::borrowBook();
if ($this->borrowedBook == NULL) {
$this->haveBook = FALSE;
} else {
$this->haveBook = TRUE;
}
}
function returnBook() {
$this->borrowedBook->returnBook($this->borrowedBook);
}
}
/*
* Initialization
*/
writeln('BEGIN TESTING SINGLETON PATTERN');
writeln('');
$bookBorrower1 = new BookBorrower();
$bookBorrower2 = new BookBorrower();
$bookBorrower1->borrowBook();
writeln('BookBorrower1 asked to borrow the book');
writeln('BookBorrower1 Author and Title: ');
writeln($bookBorrower1->getAuthorAndTitle());
writeln('');
$bookBorrower2->borrowBook();
writeln('BookBorrower2 asked to borrow the book');
writeln('BookBorrower2 Author and Title: ');
writeln($bookBorrower2->getAuthorAndTitle());
writeln('');
$bookBorrower1->returnBook();
writeln('BookBorrower1 returned the book');
writeln('');
$bookBorrower2->borrowBook();
writeln('BookBorrower2 Author and Title: ');
writeln($bookBorrower1->getAuthorAndTitle());
writeln('');
writeln('END TESTING SINGLETON PATTERN');
function writeln($line_in) {
echo $line_in.'<br/>';
}
?>