Design Patterns: The Adapter Pattern in Java
by Riley MacDonald, September 17, 2017

The Adapter pattern may appear to be similar to the Facade Pattern but in actuality it’s quite different. The Facade Pattern simplifies interactions with various interfaces while the Adapter Pattern makes a connection between classes that otherwise couldn’t due to incompatible interfaces. It does so by converting an interface of a class into something the client is expecting.

Example Problem
Consider the following classes; Television and Nintendo. The Television is brand new and only accepts HDMICable input. The Nintendo only outputs RFCable. How do you connect the two together to play some classic games?

1
2
3
4
5
6
7
8
9
10
11
public class Televsion {
    void input(HDMICable hdmiCable) {
        displayVideo();
    }
}
 
public class Nintendo {
    public RFCable output() {
        outputVideo();
    }
}

Implementing the Adapter Pattern
By writing an adapter you can build a bridge to connect the two devices together. This example omits the actual code which converts HDMI to RF output.

1
2
3
4
5
public class RFCableToHDMIAdapter extends RFCable {
    public HDMICable convert(RFCable rfCable) {
        // convert the video
    }
}

The client can “connect” the Nintendo to the Television as expected using the new RFCableToHDMIAdapter class.

1
2
3
4
5
6
7
8
9
10
public class AdapterTest {
    Televsion televsion = new Televsion();
    Nintendo nintendo = new Nintendo();
 
    RFCableToHDMIAdapter adapter = new RFCableToHDMIAdapter();
 
    public AdapterTest() {
        televsion.input(adapter.convert(nintendo.output()));
    }
}

Summary
When a classes interface isn’t the one you need, use an Adapter to resolve the issue. Keep in mind; this example programs to implementation not interface. It’s programmed to implementation only to simplify the code / example. Consider all of the classes above to be implementations of interfaces.

Open the comment form

Leave a comment:

Comments will be reviewed before they are posted.

User Comments:

My Design Patterns Catalog | Riley MacDonald on 2017-11-10 15:09:42 said:
[…] Adapter: The Facade Pattern simplifies interactions with various interfaces while the Adapter Pattern makes a connection between classes that otherwise couldn’t due to incompatible interfaces. […]