Search code examples
design-patternsadapter

Use Adapter Pattern rather than refactor code from Enumerator to Iterator


I read Head First Design Patterns 2004 on page 248 about Adapter Pattern in real world.
It talks about an old Java application using Enumerator but now it becomes a legacy code, which Java no longer maintains it anymore.
The resolution is by using Adapter pattern to adapts Enumerator with Iterator (new Java release).

Why don't they just refactor(edit) the code from Enumerator to Iterator instead of using the pattern?


Solution

  • First of all, I would like to point out Enumeration is not yet deprecated . You can use Enumeration and Iterator freely. The wording you used is a bit misleading (at least to me).

    What the book suggested is that, in some legacy APIs , it is possible that they may expose the Enumeration interface but not Iterator interface. For example, you are using a library in your program which contains a method that will return Enumeration<T>, and that legacy class does not provide you a method to get the iterator at all.

    In this case, you would probably want to make an adapter class if you want to have an iterator available for your program. Can you edit the code of the legacy library? Yes, of course but it is always a bad idea to modify an external library code that you are using. You may check out this thread: Java Intellij: Make change on external lib code and take effect immediately