Adapter (computing)
In computer science, an adapter is a design pattern that allows interfaces of incompatible classes to work together. It acts as a bridge, converting the interface of a class into another interface that a client expects. This pattern is particularly useful when you want to use an existing class but its interface does not match the one you need.
The adapter achieves this by wrapping the "adaptee" (the existing class with the incompatible interface) and exposing a new interface that the client can use. The client interacts with the adapter, which in turn translates the client's requests into calls that the adaptee understands.
The adapter pattern can be implemented in different ways, broadly categorized as:
-
Object Adapter: Uses object composition. The adapter holds an instance of the adaptee and delegates calls to it. This is generally favored over class adapter because it promotes loose coupling.
-
Class Adapter: Uses inheritance. The adapter inherits from both the target interface and the adaptee class. This approach is less flexible as it requires multiple inheritance, which is not supported in some languages.
Key Benefits:
- Reusability: Allows you to reuse existing classes without modifying their source code.
- Flexibility: Enables incompatible interfaces to collaborate.
- Maintainability: Separates the client from the specific implementation of the adaptee, making it easier to change or replace the adaptee without affecting the client.
- Single Responsibility Principle: Adheres to the single responsibility principle by isolating the interface conversion logic.
Common Use Cases:
- Integrating legacy systems with modern systems.
- Using third-party libraries with incompatible interfaces.
- Providing a consistent interface to different implementations of a component.