Structural Design Patterns in Java: Adapter Design Pattern

Abdulaziz Pulatjonov
DevOps.dev
Published in
3 min readJun 2, 2022

--

The Adapter Design Pattern is used to connect two incompatible classes using the interface to wrap an existing class and make it compatible with the client’s interface.

Let’s consider the case where we have an application that converts days into months. And now we want to add a new feature to that application that enables the user to convert the inserted days into weeks. To meet this need we will create an adapter that converts the returning months into weeks.

First, we will create the interface of Months which is supposed to convert inserted days to months:

And now we will create an implementation of this interface:

Then we will create an adapter interface that functions almost the same as the previous interface but returns not months but weeks:

And its implementation consists of one more private method to convert months to weeks:

And now it is complete. Of course, we could modify the “ConvertMonths” class to get the desired result, however, this pattern provides the opportunity to flex the code without changing the base code but adding new features. This improves the flexibility of the application for future changes and eases maintenance.

And now this assertion will be true:

As we can see here, the adapter converted the days into weeks.

The usage of this pattern is when we want to use the component’s functionality that is not compatible with the current application or when we want to reuse some codes without modifying them.

Structural Design Patterns state the most suitable solutions to design complex structured applications with multiple classes and objects. They help to simplify the relations of the objects and classes by focusing on how they are connected with each other.

The code is available in the Github project.

There are 6 more Structural Design Patterns that are:

  1. Bridge Design Pattern
  2. Composite Design Pattern
  3. Decorator Design Pattern
  4. Facade Design Pattern
  5. Flyweight Design Pattern
  6. Proxy Design Pattern

--

--

BS in Business Information Systems. Interests: Computer Science, Engineering, Public speaking, Languages, Music, Reading, Writing and so on