设计模式 外观模式

WechatIMG34.jpeg

介绍

外观模式是一种结构型设计模式,它提供了一个简单的接口,隐藏了复杂的子系统的实现细节,使得客户端可以更容易地使用这些子系统。外观模式的作用类似于建筑物的外观,它隐藏了建筑物内部的复杂结构和机制,使得人们可以更容易地使用建筑物。

角色

角色 说明
Client 客户角色
Facade 外观角色,提供高级接口
SubSystem 子系统角色,负责各自的功能实现

角色示例

类名 担任角色 说明
Phone 客户角色 手机
Reboot 外观角色 重启
Shutdown 子系统角色 关机
Boot 子系统角色 开机

UML类图

外观模式.jpg

代码

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
<?php 
class Shutdown
{
public function execute()
{
return "关机".PHP_EOL;
}
}

class Boot
{
public function execute()
{
return "开机".PHP_EOL;
}
}

class Reboot
{
protected $shutdown;
protected $boot;

function __construct()
{
$this->shutdown = new Shutdown();
$this->boot = new Boot();
}

public function execute()
{
return $this->shutdown->execute().$this->boot->execute();
}
}

class Phone
{
public $reboot;

function __construct()
{
$this->reboot = new Reboot();
}
}

$phone = new Phone();
echo $phone->reboot->execute();

创建 Reboot.php,内容如上。

执行

1
2
3
$ php Reboot.php
关机
开机
-------------本文结束感谢您的阅读-------------
0%