What is the adapter design pattern?

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.

Parts of the pattern

There are three parts of the pattern:

  1. Client: The class which has a reference of an interface that it can recognize.
  2. Adaptee: The unfamiliar class which the client needs to use.
  3. Adapter: A class introduced as an intermediary between the client and the adaptee. This class must implement the interface referenced by the client and also hold a reference to the adaptee.

UML diagram

svg viewer

Implementation

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

Copyright ©2025 Educative, Inc. All rights reserved