The Adapter is known as a structural pattern, as it’s used to identifying a simple way to realize relationships between entities.
Convert the interface of a class into another interface clients expect. Adapter helps two incompatible interfaces to work together.
So How Does It Work In Java?
The following example shows a simple implementation of the pattern. Consider that we have a third party library that provides sorting functionality through it’s NumberSorter class. This is our Adaptee.
/* * This is our adaptee, a third party implementation of a * number sorter that deals with Lists, not arrays. */ public class NumberSorter { public List<Integer> sort(List<Integer> numbers) { //sort and return return new ArrayList<Integer>(); } }
Our Client deals with primitive arrays rather than Lists. For the sake of this example, lets say we can’t change the client to use Lists.
int[] numbers = new int[]{34, 2, 4, 12, 1}; Sorter sorter = new SortListAdapter(); sorter.sort(numbers);
We’ve provided a Sorter interface that expects the client input. This is our target.
//this is our Target interface public interface Sorter { public int[] sort(int[] numbers); }
Finally, the SortListAdapter implements our target interface and deals with our adaptee, NumberSorter
public class SortListAdapter implements Sorter { @Override public int[] sort(int[] numbers) { //convert the array to a List List<Integer> numberList = new ArrayList<Integer>(); //call the adapter NumberSorter sorter = new NumberSorter(); numberList = sorter.sort(numberList); //convert the list back to an array and return return sortedNumbers; } }
Downsides:
Some say that the Adapter pattern is just a fix for a badly designed system, which didn’t consider all possibilties. While this is a fair point, it is an important part of a pluggable architecture. It can also add a level of complexity to your code, making debugging more difficult.