The adapter design pattern is a structural design pattern. It is used when a client class has to use another class (adaptee) that it cannot recognize. This unfamiliar class is wrapped inside another class (adapter), and enables the client to use the functionality of the adaptee.
There are three parts of the pattern:
The above UML diagram has been implemented below in C++ and Java:
#include <iostream>using namespace std;// The interface:class SmartPhone{public:virtual void use() = 0;};// A class recognized by the User// because it implements the SmartPhone interface:class Phone1: public SmartPhone{public:void use(){cout << "Using a normal smart phone." << endl;}};// Adaptee:class OldPhone{public:void foo(){cout << "Using an old phone." << endl;}};// Adapter class implements the SmartPhone interface:class OldPhoneAdapter: public SmartPhone{private:// Reference to the Adaptee:OldPhone* op;public:OldPhoneAdapter(OldPhone* op){this->op = op;}void use(){op->foo();}};// Client class:class User{private:SmartPhone* phone;public:User(SmartPhone* p){phone = p;}SmartPhone* getPhone(){return phone;}void setPhone(SmartPhone* p){phone = p;}};int main(){// Create a User of a normal SmartPhone:User* u = new User(new Phone1());// Use a normal SmartPhone:u->getPhone()->use();// Change phone to OldPhone using OldPhoneAdapter:u->setPhone(new OldPhoneAdapter(new OldPhone()));// Use an OldPhone:u->getPhone()->use();return 0;}
Free Resources