This week I read an article about the Adapter pattern, written by James Sugrue in the DZone website.
I liked the real world analogy Sugrue gave for the easy understanding of the Pattern. The example he provided for the adapter pattern is based around AC power adapters. Say we’re visiting Europe from the US, with our laptop, which expects a US power supply. To get our laptop plugged in, we’re going to need to get a power adapter that accepts our US plug and allows it to plug in to the European power outlet. The AC adapter knows how to deal with both sides, acting as a middleman – this is the adapter pattern.
The Adapter is known as a structural pattern, as it’s used to identifying a simple way to realize relationships between entities. The definition of Adapter states: Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.
The classic diagram definition of the adapter pattern is given below:
The Target interface defines the domain specific interface that the Client used, so the client collaborates with objects that implement the Target interface. On the other side of things, the Adaptee is the existing interface that needs adapting in order for our client to interact with it. The Adapter adapts the Adaptee to the Target interface – in other words, it translates the request from the client to the adaptee.
The main use of this pattern is when a new system wants to interact with legacy system using new interface which is not compatible with interface of legacy system. Moreover, when a class that we need to use doesn’t meet the requirements of an interface. For a particular object to contribute to the Properties view, adapters are used display the objects data. The view itself doesn’t need to know anything about the object the it is displaying properties for.
Some say that the Adapter pattern is just a fix for a badly designed system, which didn’t consider all possibilities. While this is a fair point, it is an important part of a pluggable architecture. It can also add a level of complexity to our code, making debugging more difficult.
After reading the article, I think in the integration aspects Adapter pattern is a time saver. I think that the adapter gives a great solution for legacy systems, and it doesn’t imply bad design. Even with a very good design, class which was once created would become a legacy class as more and more clients start using it. So, at one point of time, we might have to use adapters. With that being said, I think it’s true that adapter adds a level of complexity to our code. If there are no proper naming conventions and comments, the code is difficult to follow through. I believe we can minimize the complexity by modularizing the legacy class and adapter in separate files.
Source: https://dzone.com/articles/design-patterns-uncovered-0