The adapter pattern is used when a client class has to call an incompatible provider class. Let's imagine a MailingClient class that needs to call a method on the LegacyEmployee class:
MailingClient already calls classes that implement the
IEmployee interface but the
LegacyEmployee doesn't implement it. We could add a new method to
LegacyEmployee to implement the
IEmployee interface but
LegacyEmployee is legacy code and can't be changed. We could modify the
MailingClient class to call
LegacyEmployee but it needs to change every call. The formatting code would be duplicated everywhere. Moreover,
MailingClient won't be able to call other provider class that implement the
IEmployee interface any more.
So the solution is to code the formatting code in another independent class, an adapter, also called a wrapper class:
EmployeeAdapter implements the
EmployeeAdapter formats the data and calls
LegacyEmployee. This type of adapter is called an object adapter. The other type of adapter is the class adapter.
Think twice before implementing this pattern. This pattern should not be planned at design time. If you plan to use it for a project from scratch, this means that you don't understand this pattern. It should be used only with legacy code. It is the least bad solution.
Its implementation is easy but can be expensive. You should not have to refactor the code as the client and the provider should not be able to work together yet.
This is the worst part. Most of the code has redundancies (but less than without the pattern). The modern interface should always provide as much information as the legacy interface needs to work. If one information is missing on the modern interface, it can call the pattern into question.
This pattern can be easily removed as automatic refactoring operations can easily remove its existence.
- Put the adapter term in the name of the adapter class to indicate the use of the pattern to the other developers.