Design Pattern Download: The Adapter Pattern
The Adapter (or Wrapper) pattern is a Structural Pattern used in software engineering when you want to allow incompatible objects to interact.
Example
Imagine you are a US resident traveling to England, you have just landed at Heathrow and are about to sit down at the cafe to order some tea and scones while you call yourself an uber. oh no! your phone is dead :/ so you pull out your charger to plug into a nearby socket. However — despite your best attempts — you cannot force your 3-prong US plug into the two prong EU socket. You need an adapter! Luckily the airport is happy to sell you one (at a large premium) now you can charge your phone and head on out to Buckingham Palace.
When to use the Adapter?
- When you want to utilize an existing class but have incompatible interfaces (i.e. EU vs US interface)
What is the Builder Pattern composed of?
- The Target Service (this is the class we want to interact with, in our case this is the EUSocket)
- The Existing Object (this is a class which we currently have but is incompatible with our Service, in our case this is the US plug)
- The Adapter Class (this is a class which takes in a reference to our existing object and allows it to interact with our service, in this case it is our adapter)
Implementation
The Target Service
This is a socket which has a method to send voltage through a given EU plug.
The Existing Object
Here we have the US plug we flew into the airport with it is useless right now.
The Adapter (and EU plug)
Here we have our Adapter, the adapter has a built in European plug (target object). In our constructor we take in US plug (existing object) we can then create the EU plug using the values in the US plug we are given (or call some corresponding method in the US plug class when we need some EU functionality). The EU plug is shown below.