Skip to content

Adapter

Dmitriy Kotov edited this page Jan 10, 2017 · 2 revisions

Overall information

Structural pattern

Adapts class with functionality that satisfies client needs, but has different interface, to an interface that is used by client.

Based on UML diagram above, Adaptor adapts Adaptee to the interface, that is more common for Client class.


Advantages:

+ Allows to encapsulate third-party libraries API (which we don't control) behind Adapter class. That point brings multiple benefits, such as:

  • If third-party API changes we only need to change our Adapter class and not the client's code.

  • If we want to change implementation of third-party Adaptee class to another one (For example Gson to Jackson or to our custom implementation) - we will only need to change Adapter class and not the client's code.


Project example:

In this project we have example with the following model:

We have client's interface - Serializer, that has two methods:

  • read(path : Path) : Data - Reads data from given path
  • write(data :Data) : Path - Stores data from given object with given resourceName

And at that time we want to implement Serializer that will work with JSON format. Since there are a lot of existing third-party solutions, that will satisfy our needs, we will not create our own.

Let's say we decided to stick with Gson library, but too bad it does not implement our interface Serializer. We could use it directly in our client's code, but that is very risky, since we might want to change Gson to something else some day and we will need to change it everywhere we used it.

So, to avoid it, we want to hide it behind our own Adapter class, which is called JsonSerializer.

This class implements Serializer class and it uses Gson library functionality to satisfy our client's code needs.

Clone this wiki locally