8

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.

skaffman
  • 398,947
  • 96
  • 818
  • 769
David Parks
  • 30,789
  • 47
  • 185
  • 328

1 Answers1

19

It looks like you can use the decorator pattern and write e.g. a 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. All other methods are simply delegated to the underlying Email instance.

This is similar to how a java.io.BufferedReader works, for example. It can decorate any Reader to give it a buffering feature. 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.

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.

See also

  • Effective Java 2nd Edition, Item 16: Favor composition over inheritance
  • Effective Java 2nd Edition, Item 17: Design and document for inheritance, or else prohibit it

Related questions

Community
  • 1
  • 1
polygenelubricants
  • 376,812
  • 128
  • 561
  • 623
  • This is great, I've read a number of tutorials on this pattern. But I don't quite grasp it fully: If I need an HtmlEmail (it extends Email), and all I need is to add functionality to Email.send(), do I also need a ConcreteDecorator for HtmlEmail (and in turn for all other subclasses of Email - SimpleEmail & MultiPartEmail, implementing all respective methods to forward on to the concrete object)? – David Parks Aug 23 '10 at 20:50
  • @David: You have concrete decorators for each decoration. So you may have a `ThrottledEmail` which throttles the send of any `Email`, and you may later have further decorations on other aspects of `Email` (e.g. `AutosignedEmail` or whatever), and you can stack these on top of each other. It shouldn't really matter whether you're decorating a `HtmlEmail` or a `SimpleEmail`. – polygenelubricants Aug 23 '10 at 21:59