简体   繁体   English

Java:当其他类已经扩展基类时,如何扩展基类?

[英]Java: How to extend a base class when other classes already extend the base?

I want to extend a base class in apache commons email, the base class is Email. 我想在apache commons电子邮件中扩展一个基类,基类是Email。 I simply want to add some throttling to the .send() method 我只是想为.send()方法添加一些限制

3 other classes extend Email: HtmlEmail, SimpleEmail, and MultiPartEmail 其他3个类扩展Email:HtmlEmail,SimpleEmail和MultiPartEmail

There is no factory method for creating these 3 derived classes. 没有工厂方法来创建这3个派生类。

Is there a best way that I can extend this one method from the base Email class? 有没有一种方法可以从基础电子邮件类扩展这一方法? All I can think of is to extend the 3 derived classes, override .send() in each, and have each of them call a common static method to accomplish the .send() throttling functionality. 我能想到的是扩展3个派生类,在每个派生类中重写.send(),并让它们中的每一个调用一个通用的静态方法来完成.send()限制功能。

It looks like you can use the decorator pattern and write eg a ThrottledEmail . 看起来您可以使用装饰器模式并编写例如ThrottledEmail It simply decorates another instance of Email (it can be ANY Email subclass) and it can @Override the send method to enforce some throttling. 它只是装饰另一个Email实例(它可以是任何 Email子类),它可以@Override send方法来强制执行一些限制。 All other methods are simply delegated to the underlying Email instance. 所有其他方法都只是委托给底层的Email实例。

This is similar to how a java.io.BufferedReader works, for example. 例如,这类似于java.io.BufferedReader工作方式。 It can decorate any Reader to give it a buffering feature. 它可以装饰任何Reader ,使其具有缓冲功能。 Other examples include java.util.Collections that provides utility methods such as Collection<T> synchronizedCollection(Collection<T>) which wraps ANY Collection<T> and decorates it with synchronization features. 其他示例包括java.util.Collections ,它提供实用程序方法,如Collection<T> synchronizedCollection(Collection<T>) ,它包装ANY Collection<T>并使用同步功能对其进行装饰。

Unless the base class is clearly documented to facilitate subclasses to @Override certain methods, you should generally favor composition ( has-a ) over inheritance ( is-a ) relationship. 除非明确记录基类以便于@Override某些方法的子类,否则通常应该@Override组合( has-a )而不是继承( is-a )关系。

See also 也可以看看

  • Effective Java 2nd Edition, Item 16: Favor composition over inheritance 有效的Java第2版,第16项:支持组合而不是继承
  • Effective Java 2nd Edition, Item 17: Design and document for inheritance, or else prohibit it 有效的Java第2版,第17项:继承的设计和文档,或者禁止它

Related questions 相关问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM