Structural Patterns  «Prev  Next»

Adapter Pattern

Description of the Adapter Pattern:

The Adapter pattern acts as an intermediary between two classes, converting the interface of one class so that it can be used with the other. This enables classes with incompatible interfaces to work together. The Adapter pattern implements an interface known to its clients and provides access to an instance of a class not known to its clients. An adapter object provides the functionality of an interface without having to know the class used to implement that interace.

The Adapter pattern acts as an intermediary between 2 classes.

Adapter Pattern Java Code


The following lists the benefits of using the Adapter pattern:
  1. Allows two or more incompatible objects to communicate and interact
  2. Improves resuability of older functionality

When to use:

  1. You want to use an existing class, and its interface does not match the interface you need.
  2. You want to create a reusable class that cooperates with unrelated or unforesen classes, that is, classes that do not necessarily have compatible interfaces.
  3. You want to use an object in an environment that expects an interface that is different from the object's interface.
  4. Interface translation among multiple sources must occur.

In computer programming, the adapter pattern (often referred to as the wrapper pattern or simply a wrapper) is a design pattern that translates one interface for a class into a compatible interface.
An adapter allows classes to work together that normally could not because of incompatible interfaces, by providing its interface to clients while using the original interface. The adapter translates calls to its interface into calls to the original interface, and the amount of code necessary to do this is typically small.
The adapter is also responsible for transforming data into appropriate forms. For instance, if multiple boolean values are stored as a single integer (i.e. flags) but your client requires a 'true'/'false', the adapter would be responsible for extracting the appropriate values from the integer value.
Another example is transforming the format of dates (i.e. YYYYMMDD to MM/DD/YYYY or DD/MM/YYYY).