Adapter Design Pattern

07/05/2011

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 posted on 07/05/2011.
Ads by Google

59 comments on “Adapter Design Pattern

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

  2. Correct the spelling mistake of recangularish.

  3. Why we prefer composition over inheritance?

    • 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. 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.

    • Client : RectangularPlug
      Adapter : RectangularAdapter
      Adaptee : CylindericalSocket

  5. Please can you tell Advantages & Disadvantages

  6. Pingback: Java Pins

  7. 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. Pingback: 31 Java Links – Billmann IT BLOG

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

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

  11. 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. :)

  12. 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..

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

  14. Pingback: Bridge Design Pattern

  15. Good one!!!!

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

    Keep writing….

  16. good explanation,

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

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

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

  19. 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

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

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

  22. 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

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

  24. 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.

  25. 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?

  26. 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.

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

  28. 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?

  29. 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

  30. Thanks for this easy explanation and example!

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

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

  33. 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

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

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

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

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

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

  38. 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

  39. Pingback: Proxy Design Pattern

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>