Adapter Design Pattern

An adapter helps two incompatible interfaces to work together. This is the real world definition for an adapter. Adapter design pattern is used when you want two different classes with incompatible interfaces to work together. The name says it all. Interfaces may be incompatible but the inner functionality should suit the need.

In real world the easy and simple example that comes to mind for an adapter is the travel power adapter. American socket and plug are different from British. Their interface are not compatible with one another. British plugs are cylindrical and American plugs are recangularish. You can use an adapter in between to fit an American (rectangular) plug in British (cylindrical) socket assuming voltage requirements are met with.

How to implement adapter design pattern?

Adapter design pattern can be implemented in two ways. One using the inheritance method and second using the composition method. Just the implementation methodology is different but the purpose and solution is same.

Adapter implementation using inheritance

When a class with incompatible method needs to be used with another class you can use inheritance to create an adapter class. The adapter class which is inherited will have new compatible methods. Using those new methods from the adapter the core function of the base class will be accessed. This is called “is-a” relationship. The same real world example is implemented using java as below. Dont worry too much about logic, following example source code attempts to explain adapter design pattern and the goal is simplicity.

public class CylindricalSocket {
	public String supply(String cylinStem1, String cylinStem1) {
		System.out.println("Power power power...");
	}
}

public class RectangularAdapter extends CylindricalSocket {
	public String adapt(String rectaStem1, Sting rectaStem2) {
		//some conversion logic
		String cylinStem1 = rectaStem1;
		String cylinStem2 = rectaStem2;
		return supply(cylinStem1, cylinStem2);
	}
}

public class RectangularPlug {
	private String rectaStem1;
	private String rectaStem2;
	public getPower() {
		RectangulrAdapter adapter = new RectangulrAdapter();
		String power = adapter.adapt(rectaStem1, rectaStem2);
		System.out.println(power);
	}
}
Ads by Google

Adapter implementation using composition

The above implementation can also be done using composition. Instead of inheriting the base class create adapter by having the base class as attribute inside the adapter. You can access all the methods by having it as an attribute. This is nothing but “has-a” relationship. Following example illustrates this approach. Difference is only in the adapter class and other two classes are same. In most scenarios, prefer composition over inheritance. Using composition you can change the behaviour of class easily if needed. It enables the usage of tools like dependency injection.

public class CylindricalSocket {
	public String supply(String cylinStem1, String cylinStem1) {
		System.out.println("Power power power...");
	}
}

public class RectangularAdapter {
	private CylindricalSocket socket;

	public String adapt(String rectaStem1, Sting rectaStem2) {
		//some conversion logic
		socket = new CylindricalSocket();
		String cylinStem1 = rectaStem1;
		String cylinStem2 = rectaStem2;
		return socket.supply(cylinStem1, cylinStem2);
	}
}

public class RectangularPlug {
	private String rectaStem1;
	private String rectaStem2;
	public getPower() {
		RectangulrAdapter adapter = new RectangulrAdapter();
		String power = adapter.adapt(rectaStem1, rectaStem2);
		System.out.println(power);
	}
}

Adapter design pattern in java API

java.io.InputStreamReader(InputStream)
java.io.OutputStreamWriter(OutputStream)

This Design Patterns tutorial was added on 07/05/2011.

«

»

Comments on “Adapter Design Pattern”

  1. mahendra

    could you add the UML Diagram for adapter design pattern as well.

  2. Maniganda Prakash

    Correct the spelling mistake of recangularish.

  3. Dev Ghotkule

    Why we prefer composition over inheritance?

    • Siddhanta Pattnaik

      Through composition we can inject CylindricalSocket through dependency injection no need to create object of CylindricalSocket everytime .

      public class RectangularAdapter {
      @Autowire
      private CylindricalSocket socket;

      public String adapt(String rectaStem1, Sting rectaStem2) {
      //some conversion logic
      //socket = new CylindricalSocket();
      //no need to create object here
      String cylinStem1 = rectaStem1;
      String cylinStem2 = rectaStem2;
      return socket.supply(cylinStem1, cylinStem2);
      }
      }

      create object in application-context.xml

  4. Good work!

    can you please implement rest of the patterns. You tutorial looks helpful.

    Thanks.

  5. Debasis Samantaray

    I am sorry to say.
    The information here is not complete.

    The examples are suitable but complex.There is no description about who adapt whome ,and other detail.

    This pattern can be explained easily with small example.The readers expect to understand the entities and there relationship.So that reader can implement in other case easily.

  6. Narendra

    Please can you tell Advantages & Disadvantages

  7. speed

    does the RectangularAdapter class have to include CylindricalSocket object as a member variable?

    If the adapt() method in the adapter class were to use a temporary variable of CylindricalSocket class – the logic (ofcourse) would still work. Question is whether it would still be called an Adapter pattern using Composition?

    Thanks.

  8. Anonymous

    Thank you very much for writing the post. I’m having one question here and I hope to hear your teaching. I’m wondering is there any harm to rework the code and doing it without the adapter pattern, i.e.:

    public class Socket{
    public String supply(String s1, String s){
    return “wehlaetla”;
    }
    }

    public class Plug{
    Socket sock = new Socket();
    public void getPower(){
    sock.supply(s1, s2);
    }
    }

  9. Parmod

    HI Sir
    You have given nice example.
    I am really fan you

  10. Ahmad

    very nice example and now I am clear about this pattern.

    @anonymous your code:

    public class Socket{
    public String supply(String s1, String s){
    return “wehlaetla”;
    }
    }

    public class Plug{
    Socket sock = new Socket();
    public void getPower(){
    sock.supply(s1, s2);
    }
    }

    is not an example of adaptation here you are putting rectangular socket in rectangular plug. :)

  11. Anantha Prakash N

    Hi Very Nice Post i simply enjoyed reading but i am unable to understand the program.
    I think there will be a Implementer class which i could not find.
    Can you please help me in understanding the program or can you please send me a full program it will be really helpful as i have a client interview next Monday..

  12. Anonymous

    very clean explaination

  13. dinesh bansal

    very clean explaination

  14. Anonymous

    Thanks for explanation could you please give bit clear example with implementation.

  15. mukesh

    nice one

  16. Harish Mangalore

    Good one!!!!

    It would be better if you provide before and after design diagramms the way you have provided for Bridge patter.

    Keep writing….

  17. Steven Z

    I like simple but accurate things

  18. Venkata

    good explanation,

    and the best part is the usage of jargon is minimized. Generally its not the case with other resources.

  19. Shafaet

    Good explanation,Thank you. It would be great if you can add advantages of adapters.

  20. Tribhuwan

    Really Good example and precise explanation, First time i saw few blogs of yours…. Thank You.

  21. patrick

    hi

    i highly appreciate this simple examples ,kindly give a more complex example of a real world situation in a system

    example a program to save use contacts and show how the adapter pattern can be used.

    because a so simple example leaves the reader confused on how to apply the pattern in a real world application

  22. Ramani

    Adapter implementation using Aggregation will be more correct than Composition as the Socket can exist without the Adaptor, or the Socket is not destroyed if the Adaptor is destroyed.

    http://javapapers.com/oops/association-aggregation-composition-abstraction-generalization-realization-dependency/

  23. Anju Rattan

    Good and very simple to understand explaination of Adapter Patterns..Helped me alot for my assigment in South Africa University.

  24. divya

    thnx fr such a grt tutorial..
    its really beneficial..

  25. Very nice and cool example. i have learn 2 things from above explanation -
    1 – What is adapter class
    2 – What is is-a and has-a relationship

  26. devendra

    Very good example

  27. Ed

    This blog is simple and amazing. Nothing else to say.

  28. Ganesh

    The example code and explanation is good.
    I am able to understand the pattern and the concepts of compatible and incompatible from the socket perspective like rectangular or cylindarical. Consider a different scenario (not socket). From a Java programming perspective or OOPS perspective. On what basis, you will say a method is compatible or incompatible?. Is it based on the number of arguments and its types? Please explain with that scenario.

  29. Anonymous

    nice artical

  30. Manu

    Nice Stuff.Deeply Appreciated

  31. Guo SONG

    errors of codes are everywhere!

  32. Siddhanta Pattnaik

    Very Very Good tutorial…

  33. Pallavi

    Thank q so much for ure wonderful tutorials.. they r so simple to understand. Every topic that i look for i first visityour website.

    I just wanted to ask one doubt. In struts too adaptor pattern is followed ? Could you plz explain which component follows it and Y?

  34. J.

    Good work, thanks!

  35. Hi Joe,
    Your tutorials are really nice.

    But, please correct me if i am wrong…. ,

    getPower() method should have return type…. isn’t it? e.g in this case void.

  36. pank

    In your CylinderSocket class, how supply method can have String as return type?? …. :S

  37. Nikhil

    Thanks, Very nice explanation…
    I also heard of adapter pattern is used when some where we don’t want to implement all methods of interfaces
    for example :

    interface Myinterface{
    public void mymethodeone();
    public void mymethodeone();
    }

    abstract class Myadapter implements Myinterface {

    public void mymethodeone(){}
    public void mymethodeone(){}
    }

    class Myclass extends Myadapter
    {
    public void mymethodeone(){
    //my implementation here
    }
    }

    is this also a adapter pattern?

  38. Habibi

    Well done Joe. Congo.

  39. Sir,
    You are awesome and all your content is very helpful.I am a .Net guy.But always refer your site for any understanding points very clearly.
    Thanks sir

  40. Jay

    Thanks for this easy explanation and example!

  41. Amol

    Nice one!!!!
    I want to suggest some modifications though.

    RectangularAdapter should have ‘supply’ method rather than ‘adapt’ method. RectangularPlug class should be completely unaware RectangularAdapter class. Please see below code. (I am not able to indent code properly in textarea)

    class CylindricalSocket {
    public supply(String cylinStem1,String cylinStem2) {
    return(“Power power power…”);
    }
    }

    class RectangluarSocket{
    public supply(String rectaStem1, String rectaStem2) {
    return(“Power power power…”);
    }
    }
    class CylindricalSocketAdapter extends RectangluarSocket{
    private CylindricalSocket cylindricalSocket = null;
    public CylindricalSocketAdapter(CylindricalSocket socket){
    this.cylindricalSocket = socket;
    }
    public String supply(String rectaStem1,String rectaStem2) {
    String cylinStem1 = rectaStem1;
    String cylinStem2 = rectaStem2;
    return cylindricalSocket.supply(cylinStem1, cylinStem2);
    }
    }

    //Rectangluar plug knows only about RectangluarSocket. It does not know about any adapter. IT only knows about RectangularPlug

    class RectangularPlug {
    private RectangluarSocket rectangluarSocket = null;
    private String rectaStem1;
    private String rectaStem2;
    public RectangularPlug(RectangluarSocket socket){
    this.rectangluarSocket = socket;
    }
    public void getPower() {
    String power = rectangluarSocket.supply(rectaStem1, rectaStem2);
    System.out.println(power);
    }
    }
    new RectangularPlug(new CylindricalSocketAdapter(new CylindricalSocketAdapter()));

  42. jj

    what I understand is : java.io.InputStreamReader(InputStream)
    java.io.OutputStreamWriter(OutputStream) implements Decorator Pattern, please comment!

  43. rahul srivastava

    Great explanation and awesome real life example .Just one question more I am having is that when we should use composition approach and when to use inheritance one for this pattern

    • GAK

      Use class adapter:IS -A,when
      Adapter override somw of adaptees behviour,since Adpater is a subclass of Adptee
      Example WindowListener, java.awt.event.WindowAdapter

      Use Object adapter:Has -A,when
      a single adapter work with many adapters(adaptee and its subclasses)

  44. Rania

    Sir I have stil confusions . Any body help me out please ??

  45. Garfield

    The best example I could find :-)

  46. Garfield

    But holy sh… there are about 10 errors in the example. Have you written that in notepad?!

  47. Anonymous

    Very easy to understand… Extremely useful. Could understand in very few mins…

  48. Anonymous

    Why it is so complicated ?
    It is simple

    ClassA has-a ClassB to to process

    How ClassC can make fit to ClassA for the process like Class B

    Adapt it

    ClassA a = new ClassA(new ClassB())
    ClassA a1 = new ClassA(new ClassBApdator(new ClassC())

  49. NeeleshK

    Thanks for the article. A trivia- British plugsare not cylindrical AFAIK. They are rectangular too, just the rectangles are bigger size than the ones in American plugs. Indian plugs are cylindrical.

    Thanks
    Neelesh

  50. Kshitij

    Good explanation…

Your Comment