Junior — Middle
In what situations is it advisable to use the adapter pattern?
sobes.tech AI
Answer from AI
The adapter pattern is used when you need to make the interface of one class compatible with the interface of another class that the client expects. This is useful in the following situations:
- There is an existing class with the required functionality, but its interface does not fit the current task.
- You need to integrate a third-party library or module with an incompatible interface.
- It is necessary to ensure compatibility between new and legacy components.
Example: you have a class with a method oldRequest(), and the client expects a method newRequest(). The adapter implements newRequest(), internally calling oldRequest().
class OldInterface {
public:
void oldRequest() {
// old implementation
}
};
class Target {
public:
virtual void newRequest() = 0;
};
class Adapter : public Target {
OldInterface* oldObj;
public:
Adapter(OldInterface* obj) : oldObj(obj) {}
void newRequest() override {
oldObj->oldRequest();
}
};