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

查看:32
本文介绍了为什么 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.

至少根据抽象"这个词的字典含义,拥有一个包含所有实现方法的抽象类对我来说没有任何意义.

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() 就是这种情况.

Like doGet() or doPost() is this case.

推荐答案

要获得任何有用的行为,预计您必须覆盖这些方法.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/接口是完整的——但功能绝对不是.因此它被声明为抽象.

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

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

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