Convert the interface of a class into another interface clients expect, letting classes work together that couldn't otherwise because of incompatible interfaces. Use it when you want to use an existing class whose interface does not match the one you need, or when you want to create a reusable class that cooperates with unrelated classes that don't necessarily have compatible interfaces.
Examples:
- When you travel from the US to Europe with a US-plug laptop, you need a power plug adapter — it has an American-style socket on one side and a European-style plug on the other. In code, an XML-to-JSON adapter wraps an analytics library that only understands JSON, letting your XML-native app communicate with it without modifying the library.
// Class adapter: inherit interface publicly, implementation privately
class TextShape : public Shape, private TextView {
public:
BoundingBox GetBoundingBox() const {
Coord bottom, left, width, height;
GetOrigin(bottom, left);
GetExtent(width, height);
return BoundingBox(bottom, left, bottom+height, left+width);
}
Manipulator* CreateManipulator() const { return new TextManipulator(this); }
};
Synonyms: wrapper