Tutorial

Adapter Design Pattern in Java

Published on August 3, 2022
Default avatar

By Pankaj

Adapter Design Pattern in Java

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Adapter design pattern is one of the structural design pattern and its used so that two unrelated interfaces can work together. The object that joins these unrelated interface is called an Adapter.

Adapter Design Pattern

adapter design pattern, adapter design pattern in java, adapter pattern, adapter pattern java example One of the great real life example of Adapter design pattern is mobile charger. Mobile battery needs 3 volts to charge but the normal socket produces either 120V (US) or 240V (India). So the mobile charger works as an adapter between mobile charging socket and the wall socket. We will try to implement multi-adapter using adapter design pattern in this tutorial. So first of all we will have two classes - Volt (to measure volts) and Socket (producing constant volts of 120V).

package com.journaldev.design.adapter;

public class Volt {

	private int volts;
	
	public Volt(int v){
		this.volts=v;
	}

	public int getVolts() {
		return volts;
	}

	public void setVolts(int volts) {
		this.volts = volts;
	}
	
}
package com.journaldev.design.adapter;

public class Socket {

	public Volt getVolt(){
		return new Volt(120);
	}
}

Now we want to build an adapter that can produce 3 volts, 12 volts and default 120 volts. So first of all we will create an adapter interface with these methods.

package com.journaldev.design.adapter;

public interface SocketAdapter {

	public Volt get120Volt();
		
	public Volt get12Volt();
	
	public Volt get3Volt();
}

Two Way Adapter Pattern

While implementing Adapter pattern, there are two approaches - class adapter and object adapter - however both these approaches produce same result.

  1. Class Adapter - This form uses java inheritance and extends the source interface, in our case Socket class.
  2. Object Adapter - This form uses Java Composition and adapter contains the source object.

Adapter Design Pattern - Class Adapter

Here is the class adapter approach implementation of our adapter.

package com.journaldev.design.adapter;

//Using inheritance for adapter pattern
public class SocketClassAdapterImpl extends Socket implements SocketAdapter{

	@Override
	public Volt get120Volt() {
		return getVolt();
	}

	@Override
	public Volt get12Volt() {
		Volt v= getVolt();
		return convertVolt(v,10);
	}

	@Override
	public Volt get3Volt() {
		Volt v= getVolt();
		return convertVolt(v,40);
	}
	
	private Volt convertVolt(Volt v, int i) {
		return new Volt(v.getVolts()/i);
	}

}

Adapter Design Pattern - Object Adapter Implementation

Here is the Object adapter implementation of our adapter.

package com.journaldev.design.adapter;

public class SocketObjectAdapterImpl implements SocketAdapter{

	//Using Composition for adapter pattern
	private Socket sock = new Socket();
	
	@Override
	public Volt get120Volt() {
		return sock.getVolt();
	}

	@Override
	public Volt get12Volt() {
		Volt v= sock.getVolt();
		return convertVolt(v,10);
	}

	@Override
	public Volt get3Volt() {
		Volt v= sock.getVolt();
		return convertVolt(v,40);
	}
	
	private Volt convertVolt(Volt v, int i) {
		return new Volt(v.getVolts()/i);
	}
}

Notice that both the adapter implementations are almost same and they implement the SocketAdapter interface. The adapter interface can also be an abstract class. Here is a test program to consume our adapter design pattern implementation.

package com.journaldev.design.test;

import com.journaldev.design.adapter.SocketAdapter;
import com.journaldev.design.adapter.SocketClassAdapterImpl;
import com.journaldev.design.adapter.SocketObjectAdapterImpl;
import com.journaldev.design.adapter.Volt;

public class AdapterPatternTest {

	public static void main(String[] args) {
		
		testClassAdapter();
		testObjectAdapter();
	}

	private static void testObjectAdapter() {
		SocketAdapter sockAdapter = new SocketObjectAdapterImpl();
		Volt v3 = getVolt(sockAdapter,3);
		Volt v12 = getVolt(sockAdapter,12);
		Volt v120 = getVolt(sockAdapter,120);
		System.out.println("v3 volts using Object Adapter="+v3.getVolts());
		System.out.println("v12 volts using Object Adapter="+v12.getVolts());
		System.out.println("v120 volts using Object Adapter="+v120.getVolts());
	}

	private static void testClassAdapter() {
		SocketAdapter sockAdapter = new SocketClassAdapterImpl();
		Volt v3 = getVolt(sockAdapter,3);
		Volt v12 = getVolt(sockAdapter,12);
		Volt v120 = getVolt(sockAdapter,120);
		System.out.println("v3 volts using Class Adapter="+v3.getVolts());
		System.out.println("v12 volts using Class Adapter="+v12.getVolts());
		System.out.println("v120 volts using Class Adapter="+v120.getVolts());
	}
	
	private static Volt getVolt(SocketAdapter sockAdapter, int i) {
		switch (i){
		case 3: return sockAdapter.get3Volt();
		case 12: return sockAdapter.get12Volt();
		case 120: return sockAdapter.get120Volt();
		default: return sockAdapter.get120Volt();
		}
	}
}

When we run above test program, we get following output.

v3 volts using Class Adapter=3
v12 volts using Class Adapter=12
v120 volts using Class Adapter=120
v3 volts using Object Adapter=3
v12 volts using Object Adapter=12
v120 volts using Object Adapter=120

Adapter Design Pattern Class Diagram

adapter pattern class diagram, adapter design pattern, adapter pattern, adapter design pattern in java

Adapter Design Pattern Example in JDK

Some of the adapter design pattern example I could easily find in JDK classes are;

  • java.util.Arrays#asList()
  • java.io.InputStreamReader(InputStream) (returns a Reader)
  • java.io.OutputStreamWriter(OutputStream) (returns a Writer)

That’s all for adapter design pattern in java.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Pankaj

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
November 1, 2020

Hi Pankaj . Is it what you said about two unrelated interfaces(Mobile & Socket) public interface Socket { Integer getVolts(); } public interface Mobile { Integer getDesiredVolts(); } public class Socket12v implements Socket { @Override public Integer getVolts() { return 12; } } public class Socket3v implements Socket { @Override public Integer getVolts() { return 3; } } public class SocketObjectAdapter implements Mobile { // Using Composition for adapter pattern private Socket socket; public SocketObjectAdapter(Socket s) { this.socket = s; } @Override public Integer getDesiredVolts() { return socket.getVolts(); } } public class AdapterTest { public static void main(String[] args) { Socket soc3v = new Socket3v(); Mobile redmi = new SocketObjectAdapter(soc3v); System.out.println(redmi.getDesiredVolts()); Socket soc12v = new Socket12v(); Mobile onePlus = new SocketObjectAdapter(soc12v); System.out.println(onePlus.getDesiredVolts()); } }

- Awinas Kannan

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    September 19, 2020

    I think Object Adapter pattern is not Composite pattern in that the composite interface SocketAdapter has no relation with the base type Socket technically. I’d say it’s just the way how Object Adapter pattern is, or if I have to give a pattern for this then I’d say it’s more like Decorator pattern. By the way thank you for your SW design pattern posts. I’m learning about them for job interviews :)

    - Changdae Park

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      July 17, 2020

      Thanks.Very good explanation

      - Narendar Singh

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        October 20, 2019

        very good!I learned it

        - hui

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          October 11, 2019

          Thanks.Very good explanation

          - GuruRaja

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            May 7, 2019

            Thanks a lot… It is well explained…

            - Devesh

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              March 19, 2019

              It’s helpful, it is simple and detailed. I try to understand every design pattern as a designer and use it in our daily working or programming. Thanks.

              - Silent

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                March 18, 2019

                getVolt(sockAdapter,3); --> which method is actually calling ?

                - jitesh

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  July 31, 2018

                  Hi, Personally, I would inject Socket instead of letting the adapter to initialize it, e.g public SocketObjectAdapterImpl(Socket s){ this.s = s; } The reason for this change is that if you want to add setters to the Socket, then you won’t be able to set the state from the client as the reference to the object is within the state of the Adapter. I would limit the adapter’s responsibility to getting state and/or converting, nothing more. Any reason why you favour the current implementation over the DI ?

                  - Pitos

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    September 13, 2017

                    Hi Pankaj, Your example was really good, it did help me understand the adapter pattern. I referenced your post while creating my demo for the same.

                    - Yogesh

                      Try DigitalOcean for free

                      Click below to sign up and get $200 of credit to try our products over 60 days!

                      Sign up

                      Join the Tech Talk
                      Success! Thank you! Please check your email for further details.

                      Please complete your information!

                      Get our biweekly newsletter

                      Sign up for Infrastructure as a Newsletter.

                      Hollie's Hub for Good

                      Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

                      Become a contributor

                      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                      Welcome to the developer cloud

                      DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

                      Learn more
                      DigitalOcean Cloud Control Panel