I want to extend a base class in apache commons email, the base class is Email. I simply want to add some throttling to the .send() method
3 other classes extend Email: HtmlEmail, SimpleEmail, and MultiPartEmail
There is no factory method for creating these 3 derived classes.
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.
It looks like you can use the decorator pattern and write e.g. a
ThrottledEmail. It simply decorates another instance ofEmail(it can be ANYEmailsubclass) and it can@Overridethesendmethod to enforce some throttling. All other methods are simply delegated to the underlyingEmailinstance.This is similar to how a
java.io.BufferedReaderworks, for example. It can decorate anyReaderto give it a buffering feature. Other examples includejava.util.Collectionsthat provides utility methods such asCollection<T> synchronizedCollection(Collection<T>)which wraps ANYCollection<T>and decorates it with synchronization features.Unless the base class is clearly documented to facilitate subclasses to
@Overridecertain methods, you should generally favor composition (has-a) over inheritance (is-a) relationship.See also
Related questions
ForwardingListusage example