-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathAdapter.php
82 lines (68 loc) · 1.5 KB
/
Adapter.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
<?php
namespace DesignPatterns\Structural;
/**
* Adapter changes the interface of an object to adapt it to another interface.
* It is often used to make existing classes work with others without modifying their code
*/
interface BookInterface
{
public function open();
public function turnPage();
}
class Book implements BookInterface
{
public function open()
{
return "Open the book..\n";
}
public function turnPage()
{
return "Go to the next page..\n";
}
}
/**
* E-book has an other interface
*/
class Kindle
{
// do the same as open() in real book
public function turnOn()
{
return "Turn on the Kindle..\n";
}
// do the same as turnPage() in real book
public function pressNextButton()
{
return "Press next button on Kindle..\n";
}
}
class KindleAdapter implements BookInterface
{
protected $kindle;
// injecting
public function __construct(Kindle $kindle)
{
$this->kindle = $kindle;
}
public function open()
{
return $this->kindle->turnOn();
}
public function turnPage()
{
return $this->kindle->pressNextButton();
}
}
# Client code example
$book = new Book();
echo $book->open();
echo $book->turnPage();
// transform Kindle e-book to the 'simple book' interface
$book = new KindleAdapter(new Kindle());
echo $book->open();
echo $book->turnPage();
/* Output:
Open the book..
Go to the next page..
Turn on the Kindle..
Press next button on Kindle.. */