Skip to content

Latest commit

 

History

History
62 lines (39 loc) · 2.74 KB

File metadata and controls

62 lines (39 loc) · 2.74 KB

Also known as Wrapper.

Intend

" Get the interface you want from the interface you have "

Convert the interface of a class into another interface expected by the client.

Adapter allows class that have incompatible interfaces to work together.

You should use the Adapter pattern in the following situations :

  • You want to use an existing class whose interface does not match the one you expect.
  • You want to create a class that can cooperate with unrelated classes.

How it's done

UML

Participants

  • Target : The domain-specific interface that the client uses.
  • Adapter : Adapts the Adaptee interface to Target interface.
  • Adaptee : The existing interface that needs adapting.
  • Client : Uses the Target interface.

How to implement

  1. Identify the two classes constituting the Target and the Adaptee.
  • The Target class will often be a service class that you cannot change (3rd-party, legacy, dependencies...).
  • The Adaptee class is the class that would benefit from using the service class.
  1. Declare the Client interface.
  2. Create the Adapter class to follow the Client interface without implementing its methods.
  3. Add a reference to the Target to the Adapter.
  4. Implement all the methods of the Client interface in the Adapter class (The Adapter should delegate most of the work to the Target.
  5. The client will use the Adapter via the Client inerface such that it will not need any change in its code.

Note : Your Adapter will inherit publicly from Target and privately from Adaptee.

Note : UML class diagram taken from here

Pros & cons

Pros

  • Single responsability principle : It lets you separate the interface from the business logic of the programm.
  • Open/Closed principle : You can introduce new types of Adapter without breaking the client code.

Cons

  • Complexity : Overall complexity is increasing because of the need to introduce a set of new interfaces and classes. This is of course simpler, if you can change the interface of the Target without having too much changes in your code.

Notes

Did you know?

In the STL, stack, queue and priority_queue are Adaptors from deque and vector. So when you call stack::push() the underlying vector does vector::push_back()

Ressources