MVC中控制器的传统用法是否会导致违反“单一责任原则"? [英] Does the traditional use of the controller in MVC lead to a violation of the Single Responsibility Principle?

查看:72
本文介绍了MVC中控制器的传统用法是否会导致违反“单一责任原则"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Wikipedia通过以下方式描述了单一责任原则:

Wikipedia describes the Single Responsibility Principle this way:

单一责任原则"规定,每个对象都应具有单一责任,并且该责任应由类完全封装.它的所有服务都应与此职责紧密结合.

The Single Responsibility Principle states that every object should have a single responsibility, and that responsibility should be entirely encapsulated by the class. All its services should be narrowly aligned with that responsibility.

在MVC中对控制器的传统使用似乎使程序员朝着违反这一原理的方向发展.采取一个简单的留言簿控制器并查看.控制器可能有两种方法/操作:1)Index()和2)Submit(). Index()显示表单. Submit()处理它.这两种方法代表两个不同的职责吗?如果是这样,那么单一责任"是如何发挥作用的?

The traditional use of the controller in MVC seems to lead a programmer towards a violation of this principle. Take a simple guest book controller and view. The controller might have two methods/actions: 1) Index() and 2) Submit(). The Index() displays the form. The Submit() processes it. Do these two methods represent two distinct responsibilities? If so, how does Single Responsibility come in to play?

推荐答案

是的.

如果要遵循SRP,则可以将Controller分解为Dispatcher and Actions; Dispatcher将控制权分配给它的动作,在编译时(C ++模板)或运行时(Java XML,无论如何),您将组成Dispatchers和Actions.

And if you want to follow the SRP, you disaggregate your Controller into a Dispatcher and Actions; the Dispatcher dispatches control to its actions, and at compile-time (C++ templates) or at runtime (Java XML, whatever), you'd compose Dispatchers and Actions.

为什么我们不经常看到这种情况?由于Controller通常是临时"实现,因此叶级别的具体类不会被泛化,也不能被子类化.在这里,该类更多地用于方便地对代码进行分组,这些动作几乎可以肯定是非公共的(可能是私有的,也许是受保护的),仅仅是"内部实现细节.

Why don't we see this more often? Because Controllers are often "ad hoc" implementations, leaf-level concrete classes that aren't generalized and aren't meant to be subclassed. Here, the class is used more to conveniently group code, the actions are almost certainly non-public (likely private, maybe protected), "merely" internal implementation details.

如何决定要分派给哪个动作,可能的动作的数量和多样性的选择很高,并且分派和动作紧密相关.因此在实践中,将代码放在一个地方通常会更容易.

The choice of how to decide what action to dispatch to, the number and diversity of possible actions, is high, and dispatching and action are tightly-coupled. So in practice, it's often easier to just put the code together in one place.

这篇关于MVC中控制器的传统用法是否会导致违反“单一责任原则"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆