What is the adapter pattern?
sobes.tech AI
Answer from AI
The Adapter Pattern is a structural design pattern that allows classes with incompatible interfaces to work together. It acts as a wrapper, transforming the interface of one class into another expected by the client.
Application:
- Integration of third-party libraries with incompatible interfaces.
- Using existing classes in new systems without modification.
- Ensuring interaction between independently developed classes.
Example implementation (object adapter):
Suppose there is an existing class LegacyService with a method oldRequest():
class LegacyService {
public void oldRequest() {
// old code
}
}
And a new interface NewService with a method newRequest():
interface NewService {
void newRequest();
}
The adapter ServiceAdapter implements NewService and holds a reference to LegacyService:
class ServiceAdapter implements NewService {
private LegacyService legacyService;
public ServiceAdapter(LegacyService legacyService) {
this.legacyService = legacyService;
}
@Override
public void newRequest() {
// Transforming the call of the new method into the old one
legacyService.oldRequest();
}
}
The client can use LegacyService through the NewService interface:
NewService service = new ServiceAdapter(new LegacyService());
service.newRequest(); // Calls oldRequest() in LegacyService
There is also a variant — class adapter, which uses multiple inheritance (if supported by the language) or inheritance from the adaptable class and implementation of the target interface. In Java, due to the lack of multiple inheritance, it is implemented through inheritance from the adaptable class and implementation of the adapter interface, but this approach is less flexible. The object adapter is preferred because it allows adapting subclasses and avoids tight coupling.
Advantages:
- Allows the coexistence of incompatible classes.
- Encapsulates interface transformation details.
- Increases system flexibility.
Disadvantages:
- May increase complexity by adding a new class.
- Performance may slightly decrease due to an additional level of abstraction.