浅谈PHP设计模式之门面模式Facade

目的

Facade通过嵌入多个(当然,有时只有一个)接口来解耦访客与子系统,同时也为了降低复杂度。

  • Facade 不会禁止你访问子系统
  • 你可以(应该)为一个子系统提供多个 Facade

因此一个好的 Facade 里面不会有 new 。如果每个方法里都要构造多个对象,那么它就不是 Facade,而是生成器或者[抽象|静态|简单] 工厂 [方法]。

优秀的 Facade 不会有 new,并且构造函数参数是接口类型的。如果你需要创建一个新实例,则在参数中传入一个工厂对象。

UML

浅谈PHP设计模式之门面模式Facade_第1张图片

代码

Facade.php

bios = $bios;
        $this->os = $os;
    }

    /**
    * 构建基础输入输出系统执行启动方法。
    */
    public function turnOn()
    {
        $this->bios->execute();
        $this->bios->waitForKeyPress();
        $this->bios->launch($this->os);
    }

    /**
    * 构建系统关闭方法。
    */
    public function turnOff()
    {
        $this->os->halt();
        $this->bios->powerDown();
    }
}

OsInterface.php

 
 

BiosInterface.php

 
 

测试

Tests/FacadeTest.php

createMock('DesignPatterns\Structural\Facade\OsInterface');

        $os->method('getName')
            ->will($this->returnValue('Linux'));

        $bios = $this->getMockBuilder('DesignPatterns\Structural\Facade\BiosInterface')
            ->setMethods(['launch', 'execute', 'waitForKeyPress'])
            ->disableAutoload()
            ->getMock();

        $bios->expects($this->once())
            ->method('launch')
            ->with($os);

        $facade = new Facade($bios, $os);

        // 门面接口很简单。
        $facade->turnOn();

        // 但你也可以访问底层组件。
        $this->assertEquals('Linux', $os->getName());
    }
}

以上就是浅谈PHP设计模式之门面模式Facade的详细内容,更多关于PHP设计模式之门面模式Facade的资料请关注脚本之家其它相关文章!

你可能感兴趣的:(浅谈PHP设计模式之门面模式Facade)