The Adapter design pattern converts the interface of a class into another interface which is expected by the client. This design pattern is mostly used to make already existing classes work with each other without modifying it’s implementation. This design pattern is useful in cases where an existing class does all the required stuff but uses a different interface which is different from the client interface. For Design patterns basic explanation see (Design Patterns Simplified Version)
Generic model class diagram for Adapter design pattern can be explained as shown in image.
This design pattern has following major components:
1) Adaptee – This is the actual class interface which is needed by the client but can’t be accessible directly by the client.
2) Adapter – This is the class which adapts the adaptee interface and exposes the interface needed by the client.
3) Client – This class uses interface defines by the adaptor class to execute the operation.
Adapter Design Pattern Code Example:
Let’s take an example of drawing a circle problem. In below example there is a class “LegacyCircle” which draws the circle by taking input as a “Diameter” length as an input. Let’s think about a client who can give input only as “Radius” length. In this case, Adapter design pattern is a winner as Adapter Class will expose the interfaces which is needed by the client and internally maps the client request to existing class required request. Class diagram for this example is as shown in the image.
Let’s have a look on the example code for this problem:
/* Product Class */ class Circle { public: virtual void draw() = 0; }; /* Adaptee Class */ class LegacyCircle { private: double m_diameter; public: void legacyDraw() { cout<<"LegacyCircle: draw()"<<endl; } LegacyCircle(double diameter) { m_diameter = diameter; } }; /* Adapter Class */ class Adapter: public Circle, private LegacyCircle { public: Adapter(double radius): LegacyCircle(2 * radius) { cout<<"Adapter circle created for radius "<<radius<<endl; } virtual void draw() { cout<<"Adapter draw "<<endl; legacyDraw(); } };
Let’s have a look on the sample main program which creates and uses this Adapter class object to draw the circle.
int main() { Circle* circle = new Adapter(16); circle->draw(); delete circle; }
Let’s have a look on to output of this example.
Adapter circle created for radius 16 Adapter draw LegacyCircle: draw()