Sometimes there are two parts of your code that you want to work together, but they cannot because they are incompatible. This is where the Adapter Design Pattern comes in handy.
Imagine a large car manufacturing factory with multiple departments. The engineering department and the testing departments need to co-ordinate and work together, but that is not happening. The engineering team's output does not match what the testing department expects, on many levels. For example, the engineering department designs parts using imperial measurements (inches, pounds) while the testing departments expects metric measurements (centimeters, kilograms). Like this, there are many aspects which are leading to incompatibility and not understanding each other's language and expectations. To solve this, the factory introduces a small Adapter department whose whole job is to receive parts or data from Engineering, converts the measurements (e.g., inches to centimeters), and hand them off to Testing in the format it expects.
Code example:
// Engineering Department (old interface)
class EngineeringDepartment {
provideMeasurements() {
return { length: 20, unit: "inches" };
}
}
// Testing Department (expects metric)
class TestingDepartment {
testPart(part) {
console.log(`Testing part of length ${part.length} ${part.unit}`);
}
}
// Adapter Department
class EngineeringToTestingAdapter {
constructor(engineeringDept) {
this.engineeringDept = engineeringDept;
}
getMetricMeasurements() {
const imperial = this.engineeringDept.provideMeasurements();
return {
length: imperial.length * 2.54, // inches to cm
unit: "cm"
};
}
}
// Usage
const engineering = new EngineeringDepartment();
const adapter = new EngineeringToTestingAdapter(engineering);
const testing = new TestingDepartment();
const partForTesting = adapter.getMetricMeasurements();
testing.testPart(partForTesting);
Top comments (0)