为什么HTTPServlet是一个抽象类?任何功能原因? [英] Why HTTPServlet is an abstract class? Any functional reason?

查看:241
本文介绍了为什么HTTPServlet是一个抽象类?任何功能原因?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HttpServlet 是一个包含所有实现方法的抽象类。为什么它是抽象的?

HttpServlet is an abstract class with all implemented methods. Why it is abstract?

我得到的最常见的答案是限制 HttpServlet 的实例化。但还有其他方法可以做到这一点,比如私有构造函数会限制实例化。

The most common answer I got is, to restrict the instantiation of HttpServlet. But there are other ways of doing it, like a private constructor will restrict the instantiation.

我可以理解他们正在遵循模板方法设计模式。如果某些方法是抽象的,那么即使用户的业务逻辑不需要它们,用户也会最终实现所有方法。

I can understand that they are following Template Method design pattern. If some methods are abstract, user will end up implementing all of them, even if he does not need them for his business logic.

但是如果 HttpServlet 不是抽象的,用户仍然可以扩展它并覆盖require方法。

But if HttpServlet was not abstract, an user can still extend it and override the require methods.

至少通过词典'abstract'的含义',对我来说,对所有实现的方法都有一个抽象类没有任何意义。

At least by the dictionary meaning of the word 'abstract', its does not make any sense to me to have a abstract class with all implemented method.

是抽象和具体方法的组合是可以的。

Yes a combination of abstract and concrete methods are ok to have.

但是如果你要创建一个类抽象,为什么不将这些方法抽象为子类必须覆盖的?或者可能根本没有宣布它是抽象的?

But if you are making a class abstract why not make those methods abstract which the sub class has to override? or may be do not declare it as abstract at all?

喜欢 doGet() doPost()就是这种情况。

推荐答案

为了有任何有用的行为,预计你必须覆盖这些方法。 HttpServlet本身没有有用的功能。

To have any useful behaviour, it is expected that you will have to override the methods. HttpServlet does not have useful functionality on its own.

使其构造函数私有会限制子类的创建能力。

Making its constructors private would limit the ability for subclasses to be created.

HttpServlet的设计可能并不理想 - 因为在许多页面上,特别是表格,GET和POST逻辑应该至少部分地沿着共同的路径前进。然而,HttpServlet的设计理念是提供 doGet() doPost()等实现回答'不支持'错误取决于HTTP版本。如果你需要返回这样的答案,这些存根将有用于继承。

The design of HttpServlet was probably not ideal -- as on many pages, forms especially, GET and POST logic should proceed at least partly along a common path. The design idea of HttpServlet however was to offer doGet(), doPost() etc implementations answering a 'not supported' error depending on HTTP version. These stubs would be useful to inherit if you needed to return such an answer.

总之, API /接口已经完成 - 但是功能绝对不是。因此它被声明为 abstract

In summary, the API/ interface is complete -- but the functionality is definitively not. Thus it is declared as abstract.

这篇关于为什么HTTPServlet是一个抽象类?任何功能原因?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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