Problem: the output of one system my not conform to the expected input of another system.
The Adapter design pattern will help to facilitate communication between two existing systems by providing a compatible interface.

The Adapter essentially encapsulates the adaptee and presents a new interface, or appearance, to the client class. It does this by wrapping the adaptee’s interface and exposing a new target interface that makes sense to the client.
.png?raw=true)
Step1: Design the target interface
public interface IWebRequester {
public int request(Object);
}
Step 2: Implement the target interface with the adapter class
public class WebAdapter: IWebRequester{
private WebService service;
public void Connect(WebService currentService) {
this.service = currentService;
}
public int request(Object request) {
Json result = this.toJson(request);
Json response = service.request(result);
if(response != null) {
return 200;
}
else{
return 500;
}
}
}
Step 3: Send the request from the client to the adapter using the target interface.
public class WebClient {
private IWebRequester webRequester;
public WebClient(WebRequester webRequester){
this.webRequester = webRequester;
}
private Object makeObject() {...}
public void doWork() {
Object object = makeObject();
int status = webRequester.request(object);
//The rest of the work
}
}
Main program:
public class Program {
public static void Main(String[] args){
string webHost = "Host: https://ivanbrygar.com";
WebService service = new WebService(webHost);
WebAdapter adapter = new WebAdapter();
adapter.Connect(service);
WebClient client = new WebClient(adapter);
client.doWork();
}
}
WebClient doesn’t need to know anything about the WebService. The adaptee is hidden from the client by the wrapping adapter class.
One thought on “Adapter pattern”