外观模式可以为复杂系统创建一个简单的、清晰的接口。如果项目中继承了大量第三方的代码,代码有面向对象,有面向过程,我们在调用上会非常的困难。这时,我们可以通过外观类,把这些零零散散的功能继承在一个类中,方便统一调用。
常规写法
demo1.php1
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
header('Content-Type:text/html; charset=utf-8');
function getName(){
return 'My name is suse';
}
function readXml(){
return '正在读取XML';
}
class Person{
private $id;
private $name;
public function __construct($id, $name){
$this->id = $id;
$this->name = $name;
}
public function getInfo(){
return $this->id.'---'.$this->name;
}
}
echo getName();
echo '<br />';
echo readXml();
echo '<br />';
$person = new Person(1, 'suse');
echo $person->getInfo();
装饰器模式
demo2.php1
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
header('Content-Type:text/html; charset=utf-8');
function getName(){
return 'My name is suse';
}
function readXml(){
return '正在读取XML';
}
class Person{
private $id;
private $name;
public function __construct($id, $name){
$this->id = $id;
$this->name = $name;
}
public function getInfo(){
return $this->id.'---'.$this->name;
}
}
// 外观类
class Facade{
public function getName(){
return getName();
}
public function getReadXml(){
return readXml();
}
public function getPersonInfo($id, $name){
$person = new Person($id, $name);
return $person->getInfo();
}
}
$facade = new Facade();
echo $facade->getName();
echo '<br />';
echo $facade->getReadXml();
echo '<br />';
echo $facade->getPersonInfo(1, 'suse');