门面模式——请求流

Facade pattern - request flow

我知道 Facade 模式用于通过隐藏复杂的子系统交互来提供更简单的界面。

我指的是下面关于 Facade 模式的维基百科 uml:

Facade的communications/calls是否是单向请求,即只有Client1/Client2发送请求并从Facade接收响应, 但是 Facade 无法向 Client1/Client2 ?

发起请求

我说 Facade 提供单向(Client -> Facade)请求交互(通过更简单的接口),而 Mediator 促进双向(Client <-> Mediator)交互systems/classes ?

你能提供一个强调这一点的参考吗?

(1) Are the communications/calls to the Facade are uni-directional requests i.e., only Client1/Client2 sends a request and receive the response from Facade, but the Facade can't initiate a request to Client1/Client2 ?

正确。这就是为什么他们被称为客户。 Facade class 是为客户端完成工作的实际服务器(不要不必要地与 Web 服务器故事混合)。当客户不需要知道实际发生了什么而只是一个高级抽象时,Facade 是有意义的。

例如:

public class Bulb{

    public void on(){
        //logic to turn on the bulb.
    }

    public void off(){
        //logic to turn off the bulb.
    }

}

public class Fan{

    public void on(){
        //logic to turn on the fan.
    }

     public void off(){
        //logic to turn off the fan.
    }

}

public class Room{

   private Bulb bulb;
   private Fan fan;

   public void powerOff(){
        this.bulb.off();
        this.fan.off();
   }
}

在这个例子中,作为客户端,我只想调用 room.powerOff(); 。我对内部发生的事情不感兴趣。

(2) Am I correct in saying that Facade provides uni-directional (Client -> Facade) request interactions (by simpler interface) where as Mediator facilitates the bidirectional (Client <-> Mediator) interactions across the systems/classes ?

(a) Facade 提供单向(Client -> Facade)请求交互(通过更简单的接口)-> 正确。

(b) Mediator 促进双向(Client <-> Mediator)交互 -> 正确。这有点像客户端也是子系统(在 Facade 中)。 :))

是的,您在这两方面都是正确的。这是相关的引用,直接来自 GoF 书,第 282 页(强调我的)。

Facade differs from Mediator in that it abstracts a subsystem of objects to provide a more convenient interface. Its protocol is unidirectional; that is, Facade objects make requests of the subsystem classes but not vice versa. In contrast, Mediator enables cooperative behavior that colleague objects don't or can't provide, and the protocol is multidirectional.

另请注意,Facade 被归类为结构 模式,而 Mediator 是行为 模式。如果 Facade 可以发起请求,那将使其具有行为性。