Adapter Pattern in Java

The Adapter Pattern is an integral part of Structural Design Patterns in JAVA. To understand this pattern, it will be easier if one imagines the work of an adapter. An adapter is used to bridge functionality gaps between two different systems. In JAVA as well, the adapter pattern is used as a glue between two interfaces that are naturally incompatible to bridge the gap between the two.

Definition

By Definition, the Adapter Pattern bridges objects of two incompatible interfaces such that one can be used to the benefit of the other. Normally. client and server interfaces differ in usability and object type. In such cases, the adapter pattern is followed to convert objects of one class or interface into the other.

Example

A typical example of the Adapter Pattern in use is in the following program. This program will convert pounds into kg (a measurement of weight). We will begin the example by defining a fixed interface for the pounds class.

public interface Pounds {
double getWeight();         //this method will return the weight of objects in pounds
}

/*Let us set the weight of a certain object. */

public class GrandPiano implements Pounds {
@override
public double getWeight() {
return 1000;
}
}

// Below is the adapter class for the required conversion

public interface PoundAdapter {
double getWeight(); }

//the snippet below will convert pounds to kgs

public class Conversion implements PoundAdapter {
private Pounds instrument;

@override
public double getWeight() {
return conKgs(instrument.getWeight()); }

private double conKgs(double pounds) {
return pounds *0.45;
}
}

 

When should you use the Adapter Pattern?

Going by definition, the ideal use of this pattern will be when a client software or application showcases impressive functionalities that will help your program but the two interfaces are incompatible with each other. Sometimes this pattern is also used so that existing code can be reused without having to make any modifications to the current application.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.