Adapter Pattern

Adapter Pattern

Adapter Pattern

Real-World Example

Code Example

Code Structure

Object Adapter - This implementation uses the object composition principle: the adapter implements the interface of one object and wraps the other one. It can be implemented in all popular programming languages

  1. The Client is a class that contains the existing business logic of the program.

  2. The Client Interface describes a protocol that other classes must follow to be able to collaborate with the client code.

  3. The Service is some useful class (usually 3rd-party or legacy). The client can’t use this class directly because it has an incompatible interface.

  4. The Adapter is a class that’s able to work with both the client and the service: it implements the client interface while wrapping the service object. The adapter receives calls from the client via the adapter interface and translates them into calls to the wrapped service object in a format it can understand.

  5. The client code doesn’t get coupled to the concrete adapter class as long as it works with the adapter via the client interface. Thanks to this, you can introduce new types of adapters into the program without breaking the existing client code. This can be useful when the interface of the service class gets changed or replaced: you can just create a new adapter class without changing the client code.

Comparisons

 Click here to expand...

Adapter Pattern vs Facade Pattern

  • Facade defines a new interface, whereas Adapter uses an old interface. Remember that Adapter makes two existing interfaces work together as opposed to defining an entirely new one.
    • Adapter and Facade are both wrappers, but they are different kinds of wrappers. The intent of Facade is to produce a simpler interface, and the intent of Adapter is to design an existing interface. While Facade routinely wraps multiple objects and Adapter wraps a single object; Facade could front-end a single complex object and Adapter could wrap several legacy objects

Adapter Pattern vs Decorator Pattern

  • main difference is that:
    • the decorator pattern is used to add functionality to an object at run-time without changing the object's method signature(s)
    • the adapter pattern is used to change the interface of an object to adapt it to another interface (i.e. different method signature(s))
  • The decorator pattern is similar to the adapter pattern in that one service "wraps" another. However, in contrast to adapters, decorators expose the same service as what they're decorating.

Resources