'Controller' 是外观模式的示例吗?

Is a 'Controller' an example for Facade pattern?

我的问题很简单。如今,有很多前端和后端的框架都实现了 MVC(模型-视图-控制)架构。

'Controller in MVC' 是 外观设计模式 的示例吗?

好的,让我先这样说:我认为术语 "MVC" 和 "Facade" 的定义都不够好,不足以使这个问题能够简洁而绝对地回答。有许多不同的 "flavors" MVC,每个都有不同的属性。所以说清楚 "yes" 或 "no" 我认为有点自以为是,但也不是那么有用。

一般答案

我不相信 Facade 和 Controller 是一回事。

如果您查看四人组设计模式,我们不能仅通过代码结构来确定模式的含义或实现。意思是,你不能看着大多数代码然后说 "This is a X Pattern obviously"。

Facade 和 Adapter 就是一个简单的例子。从代码的角度来看,两者是相同的,所以区别不在于技术,而在于你如何使用它。您构建一个适配器以将一个复杂系统连接到另一个具有定义的 API(接口)的系统。当您为同一目的创建一个新界面时,您就构建了一个外观。意思的区别在于新建层是满足现有接口(适配器)还是创建新接口(Facade)。一写就没区别了

对于Decorator和Proxy,我们可以说同样的话。事实上,我们可以为很多人做到这一点。我在演讲的前半部分谈到了这个事实Beyond Design Patterns based on this Blog Post by the same name

原因很重要

最终,我们需要查看您编写代码的原因,以查看控制器和外观是否相同(或相似)。

为什么要编写外观:因为您想提供对复杂系统的更简单访问,通常针对特定用例。来自 Sourcemaking:

Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.

为什么要编写控制器:因为您想为 "outside user" 提供特定的功能。控制器将请求路由到您的 "model" 并与视图交互。

相同之处(将简单的界面路由到幕后更复杂的设置)。应用程序中的控制器就像 Facade 一样,它作为特定用例的更复杂应用程序的 "gateway"。

细微差别

我认为这个问题真的很有趣,因为它让我们更多地思考为什么而不是什么。如果您将控制器视为可以从多个地方调用的通用抽象概念(一种情况下从 HTTP 调用,另一种情况下从 CLI 调用),那么它确实开始看起来像 LOT门面。

但是,如果您的控制器倾向于在单个上下文中使用,那么它们看起来就不再像 Facade,而是开始看起来就像通用代码。

这里的细微差别非常重要。事实上,对我来说,简单地提出问题并思考其中的细微差别 FAR 比任何答案都重要。

正如@ircmaxell 指出的那样,回答定义不明确的问题会遇到麻烦。

为了清楚起见,我将使用 Fowler's definition of an MVC Controller(强调我的):

The presentation part of MVC is made of the two remaining elements: view and controller. The controller's job is to take the user's input and figure out what to do with it.

At this point I should stress that there's not just one view and controller, you have a view-controller pair for each element of the screen, each of the controls and the screen as a whole.

我将使用关于 Facade 的意图 的文本(来自我的 GoF 副本):

Intent

Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use.

根据这些定义,它们不是一回事。

现在,值得一提的是 GRASP Controller(不是 MVC)通常是应用程序或域层的外观:

Name: Controller Problem: What first object beyond the UI layer receives and coordinates ("controls") a system operation? Solution: Assign the responsibility to an object representing one of these choices:

  • Represents the overall “system,” a “root object,” a device that the software is running within, or a major subsystem (these are all variations of a facade controller).
  • Represents a use case scenario within which the system operation occurs (a use case or session controller)