Our ShuffledWordLibrary
and our ScrambledWordLibrary
are quite similar. They
both have a WordLibrary
field called other
, to which they delegate the
method calls. Duplicate code is problematic, because if we make a mistake,
this also gets duplicated. Instead of having to fix the code in a single
place, we have to fix it everywhere.
We are going to create a DecoratedWordLibrary
that looks similar to our
ShuffledWordLibrary
, but will be used as a common superclass for our
ShuffledWordLibrary
and ScrambledWordLibrary
. What we are creating here is
following a well-establish design pattern called the decorator pattern.
Our DecoratedWordLibrary
has a field other
that points to another
WordLibrary
, which is marked as final
and is set in the constructor (auto
generate this with ALT+Insert or right-click, Insert code). We then delete the
three empty methods and delegate them to the other field, again with
ALT+Insert or right click, Insert code.
Lastly, we mark our DelegatedWordLibrary
as abstract
, so that no one accidentally
tries to construct it directly.
We hope you enjoyed this tutorial. If you did, you will also enjoy our courses. We suggest you start with Extreme Java - Advanced Java, followed by Extreme Java - Concurrency Performance for Java 8.
We deliver relevant courses, by top Java developers to produce more resourceful and efficient programmers within their organisations.
We can help make your Java application run faster and trouble-shoot concurrency and performance bugs...