The Adapter pattern allows incompatible interfaces to work together. It acts as a bridge between two incompatible interfaces.
Major Differences:
Adapter converts one interface to another that a client expects. It is used to make existing classes work with others without modifying their source code.
Example: Suppose you have a legacy system that outputs data in XML format, but your new system expects JSON. An Adapter can convert XML to JSON.
public interface JsonData {
String getJson();
}
public class XmlData {
public String getXml() {
return "<data>example</data>";
}
}
public class XmlToJsonAdapter implements JsonData {
private XmlData xmlData;
public XmlToJsonAdapter(XmlData xmlData) {
this.xmlData = xmlData;
}
@Override
public String getJson() {
String xml = xmlData.getXml();
// Convert XML to JSON (simplified)
return "{\"data\":\"example\"}";
}
}
Summary of Differences:
- Facade simplifies the interface of a complex system.
- Adapter converts one interface to another to make incompatible interfaces work together.
- Mediator centralizes communication between objects to reduce dependencies.
Each pattern addresses different problems and is used in different scenarios to improve code maintainability and flexibility.
This pattern is defined in Design Patterns by Gamma, Helm, Johnson, and Vlissides.