Design Pattern: Adapter

Tram Ho

Question

When you want to charge your iPhone with a type C cable => use an adapter that has a type C hole and a lightning connector.

When you are using data as XML, but want to use a function of a third party library that only accepts JSON as param => use Adapter to convert XML to JSON.

In Android, you have a list item and want to display it on RecyclerView => use Adapter to convert data to each item_view .

Concept

The Adapter pattern allows the interface of an existing class to be used as another interface . It will help the existing class to work with others without changing the source code .

Sounds a bit abstract, doesn’t it? We will slowly go to peel off this confusing outer shell.

However, there are two ways to use adapters: Object Adapter and Class Adapter . We will go through each way in detail.

Object Adapter Pattern

Class diagram

We will implement the interface by delegating to the adaptee object at run-time.

I’ll explain in a little more detail:

  1. Client is an existing class that I mentioned in the concept section.
  2. Client Interface is now the parent interface of Client . Other guys who want to communicate with the Client must follow this parent interface.
  3. Service is a third party guy that only accepts JSON param as I put it.
  4. Adapter implements Client Interface and contains instance of Service class (object adaptee). Every time it calls the Adapter ‘s method, it will call this Service ‘s method.
  5. So we can work with the Service guy without editing the code in the Client .

Code sample

Class Adapter pattern

The Adapter class does not need to wrap any object because it inherits from both Client and Service .

Unfortunately Java doesn’t support multiple inheritance so we don’t have a Java code sample for this part.

Conclusion

Adapter is a design pattern quite familiar to us. Through the explanation and a bit of sample code, hope everyone understands more about it.

Reference

Share the news now

Source : Viblo