Adapter Design Pattern

Last modified on October 5th, 2014 by Joe.

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);
	}
}

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)

Comments on "Adapter Design Pattern"

  1. mahendra says:

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

  2. Maniganda Prakash says:

    Correct the spelling mistake of recangularish.

  3. Dev Ghotkule says:

    Why we prefer composition over inheritance?

  4. Code Explosion says:

    Good work!

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

    Thanks.

  5. Debasis Samantaray says:

    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 says:

    Please can you tell Advantages & Disadvantages

  7. speed says:

    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 says:

    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 says:

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

  10. Ahmad says:

    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 says:

    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 says:

    very clean explaination

  13. dinesh bansal says:

    very clean explaination

  14. Anonymous says:

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

  15. […] adapter design pattern helps it two incompatible classes to work together. But, bridge design pattern decouples the […]

  16. mukesh says:

    nice one

  17. Harish Mangalore says:

    Good one!!!!

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

    Keep writing….

  18. Steven Z says:

    I like simple but accurate things

  19. Venkata says:

    good explanation,

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

  20. Shafaet says:

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

  21. Sam says:

    good one

  22. Tribhuwan says:

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

  23. patrick says:

    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

  24. Ramani says:

    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.

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

  25. Anju Rattan says:

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

  26. divya says:

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

  27. Gaurav says:

    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

  28. devendra says:

    Very good example

  29. Ed says:

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

  30. Ganesh says:

    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.

  31. Anonymous says:

    nice artical

  32. Manu says:

    Nice Stuff.Deeply Appreciated

  33. Guo SONG says:

    errors of codes are everywhere!

  34. Siddhanta Pattnaik says:

    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

  35. Siddhanta Pattnaik says:

    Very Very Good tutorial…

  36. Pallavi says:

    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?

  37. J. says:

    Good work, thanks!

  38. pank says:

    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.

  39. pank says:

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

  40. Nikhil says:

    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?

  41. Habibi says:

    Well done Joe. Congo.

  42. Srikrishna says:

    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

  43. sima says:

    ya really

  44. Jay says:

    Thanks for this easy explanation and example!

  45. Amol says:

    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()));

  46. jj says:

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

  47. rahul srivastava says:

    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

  48. Rania says:

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

  49. Garfield says:

    The best example I could find :-)

  50. Garfield says:

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

  51. GAK says:

    Client : RectangularPlug
    Adapter : RectangularAdapter
    Adaptee : CylindericalSocket

  52. GAK says:

    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)

  53. Anonymous says:

    really nice explanation

  54. Anonymous says:

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

  55. Anonymous says:

    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())

  56. NeeleshK says:

    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

  57. […] Adapter design pattern provides a different interface from the real object and enables the client to use it to interact with the real object. But, proxy design pattern provides the same interface as in the real object. […]

  58. Kshitij says:

    Good explanation…

Comments are closed for "Adapter Design Pattern".