adapter
Convert the interface of a class into another interface that clients expect, enabling incompatible interfaces to work together.
SKILL.mdskills/code-quality/adapter/SKILL.md
GitHubAdapter
Wraps an existing class in a new interface so it can work with code that expects a different interface. Acts as a translator between two incompatible interfaces.
When to Use
- Integrating a third-party library with an incompatible interface
- Reusing existing classes that can't be modified
- Multiple classes with similar behaviour but different interfaces must be used uniformly
- Gradual migration between old and new interfaces
How to Apply
- Define the
Targetinterface that clients expect - Identify the
Adapteeclass with the incompatible interface - Create an
Adapterclass that implementsTargetand holds a reference toAdaptee - Implement each
Targetmethod by translating the call to the appropriateAdapteemethod - Clients use the
Adaptervia theTargetinterface
Example
// Existing (Adaptee) — uses XML
class XmlAnalytics {
analyzeXml(xml: string): object { return {}; /* parse xml */ }
}
// Target interface clients expect
interface Analytics {
analyze(data: object): object;
}
// Adapter
class AnalyticsAdapter implements Analytics {
constructor(private adaptee: XmlAnalytics) {}
analyze(data: object): object {
const xml = JSON.stringify(data); // convert to xml format
return this.adaptee.analyzeXml(xml);
}
}
// Client code
const analytics: Analytics = new AnalyticsAdapter(new XmlAnalytics());
analytics.analyze({ users: 42 });