Adapter Design pattern – Structural Patterns
Adapter pattern Convert the existing interfaces to a new interface to achieve compatibility and re usability of the unrelated classes in one application. Also known as Wrapper pattern. An adapter allows classes to work together that normally could not because of incompatible interfaces, by providing its interface to clients while using the original interface. The adapter translates calls to its interface into calls to the original interface, and the amount of code necessary to do this is typically small. The adapter is also responsible for transforming data into appropriate forms. . When a client specifies its requirements in an interface, you can usually create a new class that implements the interface and subclasses an existing class. This approach creates a class adapter that translates a client’s calls into calls to the existing class’s methods.
The Adapter in the Real World
The concept of an Adapter is as the name suggest. It will do what is expected It adapts one object to that of another. Suppose we have any device which will work on 10 Ampere. But we don’t have plug of 10 ampere, then we need an Adapter to work that device .In similar way this design pattern works.
The Adapter in the Software
Here also it is working as same.. When you want to work or use one class to another class that was not designed to fit together, we need a adapter class.
There are two ways of implementing the Adapter Pattern, either use the Inheritance or use the composition.
Let’s do it with the approach of Inheritance.Lets take an example.
PrintOutput.java
package structural.adapter.inheritance;
public interface PrintOutput {
public String getOutput();
}
SystemVinay.java
package structural.adapter.inheritance;
public class SystemVinay{
private String specification = "Hi ,This is adapter Design Pattern";
public String getInput() {
return specification;
}
}// End of class
Finally, there will be an adapter class. This will inherit the PrintOutput and give output for SystemVinay.
OutPutAdapter.java
package structural.adapter.inheritance;
/**
* OutPutAdapter has is the connector between
* the SystemVinayand PrintOutput so as to make the interface
* of one system to suit the client.
*/
public class OutPutAdapter implements PrintOutput {
/**
* Method coming from the interface
* SystemVinaywhich we have to make to
* fit the client SystemVinay
*
* @return Desired output of “Hi ,This is adapter Design Pattern”
*/
public String getOutput() {
SystemVinaysystem = new SystemVinay();
String output = system.getInput();
return output;
}
}// End of class
This class implements the getOutput() method of SystemVinayand sets it to fit the client output.
In- Summary We can say Adapter design pattern is – A class extends another class, takes in an object, and makes the taken object behave like the extended class.