Core Java Design Pattern : Structural Pattern : Adapter Design Pattern
Adapter Design Pattern |
Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.
Also Known As :Wrapper
Use the Adapter pattern when
- you want to use an existing class, and its interface does not match the one you need.
- you want to create a reusable class that cooperates with unrelated or unforeseen classes, that is, classes that don’t necessarily have compatible interfaces.
- (object adapter only) you need to use several existing subclasses, but it’s impractical to adapt their interface by subclassing every one. An object adapter can adapt the interface of its parent class.
It is like the problem of inserting a new three-prong electrical plug in an old two-prong wall outlet – some kind of adapter or intermediary is necessary.
Examples |
Plug.java
package com.javaskool;
/**
* The input for the plug is 5 AMP. which is a
* mismatch for a 15 AMP socket.
*
* The Plug is the client. We need to cater to
* the requirements of the Plug.
*/
public interface Plug {
public String getInput();
}
Plug5AMP.java
package com.javaskool;
public class Plug5AMP implements Plug{
public String getInput()
{
return "5 AMP";
}
}
ConnectorAdapter.java
/*
* We have a 5 Amp plug and want a 5 Amp socket so that it can work. We DO NOT have a 5 Amp socket,
* what we have is a 15 Amp socket in which the 5 Amp plug cannot fit.
* The problem is how to cater to the client without changing the plug or socket.
The Adapter Pattern can be implemented in two ways, by Inheritance and by Composition.
Here is the example of Adapter by Inheritance:
*/
package com.javaskool;
public class ConnectorAdapter {
Plug5AMP plug5;
public ConnectorAdapter(Plug5AMP plug) {
this.plug5 = plug;
}
public String getAdapterOutput(String outputFromScoket)
{
/*
* if output is same, return
*/
if (outputFromScoket.equals(plug5.getInput())) {
return outputFromScoket;
}
/*
* Else, override the value by adapterOutput
*/
else {
String adapterOutput = plug5.getInput();
return adapterOutput;
}
}
}
Socket.java
package com.javaskool;
public class Socket {
/**
* Output of 15AMP returned.
*/
public String getOutput() {
return "15 AMP";
}
}
TestDrive.java
package com.javaskool;
public class TestDrive {
public static void main(String[] args) {
// TODO Auto-generated method stub
// Taking output from the Socket
Socket socket = new Socket(); //socket of 15 Amp
String outputFromSocket = socket.getOutput(); //getting 15 AMP
// Giving away input to the Plug
ConnectorAdapter adapter = new ConnectorAdapter(new Plug5AMP());
String inputToPlug = adapter.getAdapterOutput(outputFromSocket);
System.out.println("New output by adapter is: "+inputToPlug);
}
}
Output
c:\>javac -d . *.java
c:\>java com.javaskool.TestDrive
New output by adapter is: 5 AMP
Recent Comments