- Adapter is a structural design pattern that allows objects with incompatible interfaces to collaborate.
When to Use Apater Design Patterns ?
- When you have a system create for a particular type of object
- In future came similar type of object that you want to decide based on a factory method
- But you cannot directly use that class since it is not per the new interface design for the factory method
- In such case you will use a adapter class that implements that new interface and call the existing methods inside the concrete methods that you are gonna write in the Adapter class. Best example : (A very simple Example below of Apating a Pilot Pen for a new Pen interface which was later introduced)
- Live example
- Imagine that you’re creating a stock market monitoring app. The app downloads the stock data from multiple sources in XML format and then displays nice-looking charts and diagrams for the user.
- At some point, you decide to improve the app by integrating a smart 3rd-party analytics library. But there’s a catch: the analytics library only works with data in JSON format.
Solution
You can create an adapter. This is a special object that converts the interface of one object so that another object can understand it.
An adapter wraps one of the objects to hide the complexity of conversion happening behind the scenes. The wrapped object isn’t even aware of the adapter. For example, you can wrap an object that operates in meters and kilometers with an adapter that converts all of the data to imperial units such as feet and miles.
Adapters can not only convert data into various formats but can also help objects with different interfaces collaborate. Here’s how it works:
- The adapter gets an interface, compatible with one of the existing objects.
- Using this interface, the existing object can safely call the adapter’s methods.
- Upon receiving a call, the adapter passes the request to the second object, but in a format and order that the second object expects.
Sometimes it’s even possible to create a two-way adapter that can convert the calls in both directions.
A very simple Example of how to adapt to a older class using a Apater class
package designpattern; //existing class class PilotPen{ public void mark() { System.out.println("Marking with Pilot pen"); } } //New Interface interface Pen{ public void write(); } //How can you Adapt PilotPen into Pen interface?? class PilotPenAdapter implements Pen{ private PilotPen pp = new PilotPen(); @Override public void write() { pp.mark(); } } //Using Adapter public class AdapterDemo1 { public static void main(String[] args) { Pen p = new PilotPenAdapter(); p.write(); } }
Reference :
- A good reference from refactoring guru (for images only)
- Good verbal example – Youtube