设计模式9.1-外观模式

外观模式:定义了一个统一的接口,用来访问子系统中的一群接口。
外观模式和适配器模式在实现上比较相似,但是其应用的意图有所不同。
适配器模式意图改变一个接口成另一个接口,外观模式意图将一群接口简化

在示例中,我们有一个子系统House,其中有一群接口(door light air)。
当我们回家时,要开门,打开灯,打开空调。一个回家动作统一了多个接口。


<?php
interface DoorInterface
{
    public function open();

    public function close();
}

interface LightInterface
{
    public function on();

    public function off();
}

interface AirInterface
{
    public function start();

    public function stop();
}

class Door implements DoorInterface
{
    public function open()
    {
        echo "open the door<br>\n";
    }

    public function close()
    {
        echo "close the door<br>\n";
    }
}

class Light implements LightInterface
{
    public function on()
    {
        echo "turn on the light<br>\n";
    }

    public function off()
    {
        echo "turn off the light<br>\n";
    }
}

class Air implements AirInterface
{
    public function start()
    {
        echo "start the air<br>\n";
    }

    public function stop()
    {
        echo "stop the air<br>\n";
    }
}



class House
{
    private $door;
    private $light;
    private $air;

    public function __construct(DoorInterface $door, LightInterface $light, AirInterface $air)
    {
        $this->door = $door;
        $this->light = $light;
        $this->air = $air;
    }

    public function goBackHome()
    {
        $this->door->open();
        $this->light->on();
        $this->air->start();
    }

    public function leaveHome()
    {
        $this->door->close();
        $this->light->off();
        $this->air->stop();
    }
}


class Test
{
    public function run()
    {
        $door = new Door();
        $light = new Light();
        $air = new Air();


        $house = new House($door, $light, $air);

        $house->goBackHome();
        echo "<hr>";
        $house->leaveHome();
    }
}

$test = new Test();

$test->run();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值